简单模式匹配算法

来源:《数据结构:使用C++语言描述》


  

代码:

参考:https://blog.csdn.net/scgaliguodong123_/article/details/49148017

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class SimpleMatch {
/**
* 从主串s中匹配子串t,若匹配成功则返回子串t第一次出现的起始下标;若匹配失败返回-1.
*
* @param s 主串
* @param t 子串
* @param pos 从主串的pos下标开始进行模式匹配
* @return
*/
public int Index(String s, String t, int pos) {

int i = pos;// 下标i指向主串
int j = 0;// 下标j指向子串
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) {
i++;
j++;
} else { //重头开始比对
i = i - j + 1;// 下标i回到主串的下一位置pos++
j = 0;// 下标j回到子串首端
}
}

if (j >= t.length()) {
return i - t.length(); //匹配成功,返回比对成功的主串开始下标
} else {
return -1; //匹配失败
}

}

// 测试

1
2
3
4
5
6
7
    public static void main(String[] args) {
SimpleMatch test = new SimpleMatch();
System.out.println(test.Index("goodgoogle", "google", 0)); //4
System.out.println(test.Index("goodgoogle", "google", 2)); //4
}

}

---------------- The End ----------------
0%