-
Notifications
You must be signed in to change notification settings - Fork 2
/
Que28.java
80 lines (63 loc) · 1.76 KB
/
Que28.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* @Author: Han-YLun
* @date 2019/5/11 0011
* @Version 1.0
*/
public class Que28 {
public int strStr(String haystack, String needle) {
if (needle == null || "".equals(needle)) {
return 0;
}
int index = 0;
for (int i = 0; i < haystack.length(); i++) {
if (haystack.charAt(i) == needle.charAt(index)) {
i = i + 1;
int j = index + 1;
while (j < needle.length()) {
if (i >= haystack.length()) {
return -1;
}
if (haystack.charAt(i) == needle.charAt(j)) {
i++;
j++;
} else {
break;
}
}
if (j >= needle.length()) {
return i - needle.length();
}
i -= j;
}
}
return -1;
}
public int strStr1(String haystack, String needle) {
if (needle.equals("")) {
return 0;
}
char[] hayArr = haystack.toCharArray();
char[] needArr = needle.toCharArray();
int i = 0, j = 0;
while (i < hayArr.length && j < needArr.length) {
if (hayArr[i] == needArr[j]) {
i++;
j++;
} else {
i = i - j + 1;
j = 0;
}
}
if (j >= needArr.length) {
return i - j;
} else {
return -1;
}
}
public static void main(String[] args) {
Que28 que28 = new Que28();
int i = que28.strStr("mississippi",
"issip");
System.out.println(i);
}
}