-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStrStr.java
More file actions
50 lines (33 loc) · 968 Bytes
/
StrStr.java
File metadata and controls
50 lines (33 loc) · 968 Bytes
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
public class StrStr {
// 相当于java indexOf
public int indexOf(String source,String pattern){
char first = pattern.charAt(0);
int max = source.length()-pattern.length();
for (int index = 0; index <= max; index++) {
if (source.charAt(index) != first) {
while(++index <= max && source.charAt(index) != first);
}
if (index <= max) {
int rest = index + 1;
int end = index + pattern.length();
for (int k = 1; rest < end && source.charAt(rest) == pattern.charAt(k); k++,rest++);
if (rest == end) {
return index;
}
}
}
return -1;
}
public static void main(String[] args) {
StrStr instance = new StrStr();
String source = "sfaba bcasf babca bcab ababcabababbabcab";
String pattern = "abababb";
int index = instance.indexOf(source, pattern);
if(index >= 0){
System.out.println(index);
}
else{
System.out.println("No contain");
}
}
}