-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathImplementStrStr.java
More file actions
50 lines (43 loc) · 1.31 KB
/
ImplementStrStr.java
File metadata and controls
50 lines (43 loc) · 1.31 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
package stringmatch;
// Source : https://leetcode.com/problems/implement-strstr/
// Id : 28
// Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode
// Date : 2019-11-06
// Topic : String
// Level : Easy+
// Other :
// Tips :
// Result : 53.86% 64.88%
public class ImplementStrStr {
// 1619 ms
public int strStr(String haystack, String needle) {
if (needle.isEmpty())
return 0;
if (haystack.isEmpty() || needle.length() > haystack.length())
return -1;
for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
int j = 0, tmp = i;
while (j < needle.length()) {
if (haystack.charAt(tmp) != needle.charAt(j))
break;
else {
j++;
tmp++;
}
}
if (j == needle.length())
return i;
}
return -1;
}
// 380ms
public int strStr1(String haystack, String needle) {
// public int strStr(String haystack, String needle) {
if (needle.length() == 0) return 0;
return haystack.indexOf(needle);
}
public static void main(String[] args) {
ImplementStrStr i = new ImplementStrStr();
System.out.println(i.strStr("qqhh", "hh"));
}
}