导航
导航

字符串匹配算法之Sunday算法

Sunday Algorithm

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
/**
* sunday字符串匹配算法
* @param text 目标串
* @param pattern 模式串
* @return 返回模式串在目标串中出现的起始位置,不存在返回-1
*/
public int sunday(String text, String pattern){
int patternLen = pattern.length();
int textLen = text.length();

int i = 0;
int j = 0;

while(i < textLen && j < patternLen){
if(text.charAt(i) == pattern.charAt(j)){
i++;
j++;
}else{
if(i + patternLen >= textLen)
break;

int k = isContains(pattern, text.charAt(i+patternLen));
if(k == -1)
i = i + patternLen;
else
i = i + patternLen - k;

j = 0;
}
}

if(j == patternLen)
return i - j;
else
return -1;
}

private int isContains(String pattern, char next){
for(int i = 0; i < pattern.length(); i++){
if(next == pattern.charAt(i))
return i;

}
return -1;
}