leetcode-implement-strstr

题目大意

  https://leetcode.com/problems/implement-strstr/

  实现字符串匹配判断

题目分析

  利用kmp算法,具体原理可以看下我之前的一篇博客

代码

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Solution {
public int strStr(String haystack, String needle) {
char[] txt = haystack.toCharArray();
char[] pat = needle.toCharArray();
int n = txt.length;
int m = pat.length;
if (n < m) {
return -1;
}
if (n == 0) {
return 0;
}
if (m == 0) {
return 0;
}
int[] lps = new int[m];
// build lps array
int preLen = 0;
int i = 1;
while (i < m) {
if (pat[preLen] == pat[i]) {
lps[i] = preLen + 1;
i++;
preLen++;
} else {
if (preLen == 0) {
lps[i] = 0;
i++;
} else {
preLen = lps[preLen - 1];
}
}
}
// kmp
i = 0;
int j = 0;
while (i < n) {
if (txt[i] == pat[j]) {
i++;
j++;
}
if (j == m) {
return i - j;
} else if (i < n && txt[i] != pat[j]) {
if (j > 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
return -1;
}
}