-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28.java
More file actions
61 lines (52 loc) · 1.6 KB
/
Copy path28.java
File metadata and controls
61 lines (52 loc) · 1.6 KB
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
class Solution {
public int strStr(String haystack, String needle) {
int temp = 0;
int result = -1;
if (haystack == null) {
return -1;
}
if (needle == null) {
return -1;
}
if ("".equals(haystack) && "".equals(needle)) {
return 0;
}
if (!"".equals(haystack) && "".equals(needle)) {
return 0;
}
if ("".equals(haystack) && !"".equals(needle)) {
return -1;
}
if (haystack.length() < needle.length()) {
return -1;
}
char hayChar, needleChar;
for (int i = 0;i < haystack.length();i++) {
hayChar = haystack.charAt(i);
if (temp < needle.length()) {
needleChar = needle.charAt(temp);
if (needleChar == hayChar) {
if (result == -1) {
result = i;
}
temp++;
} else {
if (result != -1) {
i = result;
}
temp = 0;
result = -1;
}
}
}
//"mississippi", "issipi" mississippi最后一个字母和issipi的第一个字母相等,需要判断长度最少是needle.length())
if (haystack.length() - result >= needle.length()) {
return result;
} else {
return -1;
}
}
public static void main(String[] args) {
System.out.println(new Solution().strStr("mississippi", "issipi"));
}
}