|
| 1 | +/* |
| 2 | + * Aho-Corasick String Matching Algorithm Implementation |
| 3 | + * |
| 4 | + * This code implements the Aho-Corasick algorithm, which is used for efficient |
| 5 | + * string matching in a given text. It can find multiple patterns simultaneously |
| 6 | + * and records their positions in the text. |
| 7 | + * |
| 8 | + * Author: Prabhat-Kumar-42 |
| 9 | + * GitHub: https://github.com/Prabhat-Kumar-42 |
| 10 | + */ |
| 11 | + |
| 12 | +package com.thealgorithms.strings; |
| 13 | + |
| 14 | +import java.util.ArrayList; |
| 15 | +import java.util.HashMap; |
| 16 | +import java.util.LinkedList; |
| 17 | +import java.util.Map; |
| 18 | +import java.util.Queue; |
| 19 | + |
| 20 | +public final class AhoCorasick { |
| 21 | + private AhoCorasick() { |
| 22 | + } |
| 23 | + |
| 24 | + // Trie Node Class |
| 25 | + private static class Node { |
| 26 | + // Represents a character in the trie |
| 27 | + private HashMap<Character, Node> child = new HashMap<>(); // Child nodes of the current node |
| 28 | + private Node suffixLink; // Suffix link to another node in the trie |
| 29 | + private Node outputLink; // Output link to another node in the trie |
| 30 | + private int patternInd; // Index of the pattern that ends at this node |
| 31 | + |
| 32 | + Node() { |
| 33 | + this.suffixLink = null; |
| 34 | + this.outputLink = null; |
| 35 | + this.patternInd = -1; |
| 36 | + } |
| 37 | + |
| 38 | + public HashMap<Character, Node> getChild() { |
| 39 | + return child; |
| 40 | + } |
| 41 | + |
| 42 | + public Node getSuffixLink() { |
| 43 | + return suffixLink; |
| 44 | + } |
| 45 | + |
| 46 | + public void setSuffixLink(final Node suffixLink) { |
| 47 | + this.suffixLink = suffixLink; |
| 48 | + } |
| 49 | + |
| 50 | + public Node getOutputLink() { |
| 51 | + return outputLink; |
| 52 | + } |
| 53 | + |
| 54 | + public void setOutputLink(final Node outputLink) { |
| 55 | + this.outputLink = outputLink; |
| 56 | + } |
| 57 | + |
| 58 | + public int getPatternInd() { |
| 59 | + return patternInd; |
| 60 | + } |
| 61 | + |
| 62 | + public void setPatternInd(final int patternInd) { |
| 63 | + this.patternInd = patternInd; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + // Trie Class |
| 68 | + public static class Trie { |
| 69 | + |
| 70 | + private Node root = null; // Root node of the trie |
| 71 | + private final String[] patterns; // patterns according to which Trie is constructed |
| 72 | + |
| 73 | + public Trie(final String[] patterns) { |
| 74 | + root = new Node(); // Initialize the root of the trie |
| 75 | + this.patterns = patterns; |
| 76 | + buildTrie(); |
| 77 | + buildSuffixAndOutputLinks(); |
| 78 | + } |
| 79 | + |
| 80 | + // builds AhoCorasick Trie |
| 81 | + private void buildTrie() { |
| 82 | + |
| 83 | + // Loop through each input pattern and building Trie |
| 84 | + for (int i = 0; i < patterns.length; i++) { |
| 85 | + Node curr = root; // Start at the root of the trie for each pattern |
| 86 | + |
| 87 | + // Loop through each character in the current pattern |
| 88 | + for (int j = 0; j < patterns[i].length(); j++) { |
| 89 | + char c = patterns[i].charAt(j); // Get the current character |
| 90 | + |
| 91 | + // Check if the current node has a child for the current character |
| 92 | + if (curr.getChild().containsKey(c)) { |
| 93 | + curr = curr.getChild().get(c); // Update the current node to the child node |
| 94 | + } else { |
| 95 | + // If no child node exists, create a new one and add it to the current node's children |
| 96 | + Node nn = new Node(); |
| 97 | + curr.getChild().put(c, nn); |
| 98 | + curr = nn; // Update the current node to the new child node |
| 99 | + } |
| 100 | + } |
| 101 | + curr.setPatternInd(i); // Store the index of the pattern in the current leaf node |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + private void initializeSuffixLinksForChildNodesOfTheRoot(Queue<Node> q) { |
| 106 | + for (char rc : root.getChild().keySet()) { |
| 107 | + Node childNode = root.getChild().get(rc); |
| 108 | + q.add(childNode); // Add child node to the queue |
| 109 | + childNode.setSuffixLink(root); // Set suffix link to the root |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private void buildSuffixAndOutputLinks() { |
| 114 | + root.setSuffixLink(root); // Initialize the suffix link of the root to itself |
| 115 | + Queue<Node> q = new LinkedList<>(); // Initialize a queue for BFS traversal |
| 116 | + |
| 117 | + initializeSuffixLinksForChildNodesOfTheRoot(q); |
| 118 | + |
| 119 | + while (!q.isEmpty()) { |
| 120 | + Node currentState = q.poll(); // Get the current node for processing |
| 121 | + |
| 122 | + // Iterate through child nodes of the current node |
| 123 | + for (char cc : currentState.getChild().keySet()) { |
| 124 | + Node currentChild = currentState.getChild().get(cc); // Get the child node |
| 125 | + Node parentSuffix = currentState.getSuffixLink(); // Get the parent's suffix link |
| 126 | + |
| 127 | + // Calculate the suffix link for the child based on the parent's suffix link |
| 128 | + while (!parentSuffix.getChild().containsKey(cc) && parentSuffix != root) { |
| 129 | + parentSuffix = parentSuffix.getSuffixLink(); |
| 130 | + } |
| 131 | + |
| 132 | + // Set the calculated suffix link or default to root |
| 133 | + if (parentSuffix.getChild().containsKey(cc)) { |
| 134 | + currentChild.setSuffixLink(parentSuffix.getChild().get(cc)); |
| 135 | + } else { |
| 136 | + currentChild.setSuffixLink(root); |
| 137 | + } |
| 138 | + |
| 139 | + q.add(currentChild); // Add the child node to the queue for further processing |
| 140 | + } |
| 141 | + |
| 142 | + // Establish output links for nodes to efficiently identify patterns within patterns |
| 143 | + if (currentState.getSuffixLink().getPatternInd() >= 0) { |
| 144 | + currentState.setOutputLink(currentState.getSuffixLink()); |
| 145 | + } else { |
| 146 | + currentState.setOutputLink(currentState.getSuffixLink().getOutputLink()); |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + private ArrayList<ArrayList<Integer>> initializePositionByStringIndexValue() { |
| 152 | + ArrayList<ArrayList<Integer>> positionByStringIndexValue = new ArrayList<>(patterns.length); // Stores positions where patterns are found in the text |
| 153 | + for (int i = 0; i < patterns.length; i++) { |
| 154 | + positionByStringIndexValue.add(new ArrayList<Integer>()); |
| 155 | + } |
| 156 | + return positionByStringIndexValue; |
| 157 | + } |
| 158 | + |
| 159 | + // Searches for patterns in the input text and records their positions |
| 160 | + public ArrayList<ArrayList<Integer>> searchIn(final String text) { |
| 161 | + var positionByStringIndexValue = initializePositionByStringIndexValue(); // Initialize a list to store positions of the current pattern |
| 162 | + Node parent = root; // Start searching from the root node |
| 163 | + |
| 164 | + PatternPositionRecorder positionRecorder = new PatternPositionRecorder(positionByStringIndexValue); |
| 165 | + |
| 166 | + for (int i = 0; i < text.length(); i++) { |
| 167 | + char ch = text.charAt(i); // Get the current character in the text |
| 168 | + |
| 169 | + // Check if the current node has a child for the current character |
| 170 | + if (parent.getChild().containsKey(ch)) { |
| 171 | + parent = parent.getChild().get(ch); // Update the current node to the child node |
| 172 | + positionRecorder.recordPatternPositions(parent, i); // Use the method in PatternPositionRecorder to record positions |
| 173 | + } else { |
| 174 | + // If no child node exists for the character, backtrack using suffix links |
| 175 | + while (parent != root && !parent.getChild().containsKey(ch)) { |
| 176 | + parent = parent.getSuffixLink(); |
| 177 | + } |
| 178 | + if (parent.getChild().containsKey(ch)) { |
| 179 | + i--; // Decrement i to reprocess the same character |
| 180 | + } |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + setUpStartPoints(positionByStringIndexValue); |
| 185 | + return positionByStringIndexValue; |
| 186 | + } |
| 187 | + |
| 188 | + // by default positionByStringIndexValue contains end-points. This function converts those |
| 189 | + // endpoints to start points |
| 190 | + private void setUpStartPoints(ArrayList<ArrayList<Integer>> positionByStringIndexValue) { |
| 191 | + for (int i = 0; i < patterns.length; i++) { |
| 192 | + for (int j = 0; j < positionByStringIndexValue.get(i).size(); j++) { |
| 193 | + int endpoint = positionByStringIndexValue.get(i).get(j); |
| 194 | + positionByStringIndexValue.get(i).set(j, endpoint - patterns[i].length() + 1); |
| 195 | + } |
| 196 | + } |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + // Class to handle pattern position recording |
| 201 | + private static class PatternPositionRecorder { |
| 202 | + private ArrayList<ArrayList<Integer>> positionByStringIndexValue; |
| 203 | + |
| 204 | + // Constructor to initialize the recorder with the position list |
| 205 | + PatternPositionRecorder(final ArrayList<ArrayList<Integer>> positionByStringIndexValue) { |
| 206 | + this.positionByStringIndexValue = positionByStringIndexValue; |
| 207 | + } |
| 208 | + |
| 209 | + /** |
| 210 | + * Records positions for a pattern when it's found in the input text and follows |
| 211 | + * output links to record positions of other patterns. |
| 212 | + * |
| 213 | + * @param parent The current node representing a character in the pattern trie. |
| 214 | + * @param currentPosition The current position in the input text. |
| 215 | + */ |
| 216 | + public void recordPatternPositions(final Node parent, final int currentPosition) { |
| 217 | + // Check if the current node represents the end of a pattern |
| 218 | + if (parent.getPatternInd() > -1) { |
| 219 | + // Add the current position to the list of positions for the found pattern |
| 220 | + positionByStringIndexValue.get(parent.getPatternInd()).add(currentPosition); |
| 221 | + } |
| 222 | + |
| 223 | + Node outputLink = parent.getOutputLink(); |
| 224 | + // Follow output links to find and record positions of other patterns |
| 225 | + while (outputLink != null) { |
| 226 | + // Add the current position to the list of positions for the pattern linked by outputLink |
| 227 | + positionByStringIndexValue.get(outputLink.getPatternInd()).add(currentPosition); |
| 228 | + outputLink = outputLink.getOutputLink(); |
| 229 | + } |
| 230 | + } |
| 231 | + } |
| 232 | + // method to search for patterns in text |
| 233 | + public static Map<String, ArrayList<Integer>> search(final String text, final String[] patterns) { |
| 234 | + final var trie = new Trie(patterns); |
| 235 | + final var positionByStringIndexValue = trie.searchIn(text); |
| 236 | + return convert(positionByStringIndexValue, patterns); |
| 237 | + } |
| 238 | + |
| 239 | + // method for converting results to a map |
| 240 | + private static Map<String, ArrayList<Integer>> convert(final ArrayList<ArrayList<Integer>> positionByStringIndexValue, final String[] patterns) { |
| 241 | + Map<String, ArrayList<Integer>> positionByString = new HashMap<>(); |
| 242 | + for (int i = 0; i < patterns.length; i++) { |
| 243 | + String pattern = patterns[i]; |
| 244 | + ArrayList<Integer> positions = positionByStringIndexValue.get(i); |
| 245 | + positionByString.put(pattern, new ArrayList<>(positions)); |
| 246 | + } |
| 247 | + return positionByString; |
| 248 | + } |
| 249 | +} |
0 commit comments