有限状态机的详细说明参见此链接
public class Test {
private static int alphaSize = 3;
private static HashMap<Integer, HashMap<Character, Integer>> jumpTable = new HashMap<>();
private String P;
public Test(String p) {
P = p;
makeJumpTable();
}
private void makeJumpTable() {
for (int i = 0; i < P.length(); i++) {
for (int j = 0; j < alphaSize; j++) {
char c = (char) ('a' + j);
String Pq = P.substring(0, i) + c;
int nextState = findSuffix(Pq);
System.out.println("from state " + i + " receive input char " + c + " jump to state " + nextState);
HashMap<Character, Integer> map = jumpTable.get(i);
if (map == null) {
map = new HashMap<>();
}
map.put(c, nextState);
jumpTable.put(i, map);
}
}
}
private int findSuffix(String s) {
int suffixLen = 0;
int i = 0;
while (i < P.length() && i < s.length()) {
if (P.charAt(i) != s.charAt(i)) {
break;
}
i++;
}
suffixLen = i;
return suffixLen;
}
public int match(String Text) {
Integer q = 0;
HashMap<Character, Integer> map = jumpTable.get(q);
for (int i = 0; i < Text.length(); i++) {
int oldState = q;
q = map.get(Text.charAt(i));
if (q == null) {
return -1;
}
System.out.println("In state " + oldState + " receive input " + Text.charAt(i) + " jump to state " + q);
if (q == P.length()) {
return q;
}
}
return -1;
}
public static void main(String[] args) {
StringAutomaton p = new StringAutomaton("abaa");
int i = p.match("bbaabaas");
System.out.println(i);
}
}