-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-28-Implement-strStr.java
45 lines (37 loc) · 1.46 KB
/
LeetCode-28-Implement-strStr.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
/*
LeetCode: https://leetcode.com/problems/implement-strstr/
LintCode: http://www.lintcode.com/problem/implement-strstr/
JiuZhang: http://www.jiuzhang.com/solutions/implement-strstr/
ProgramCreek: http://www.programcreek.com/2012/12/leetcode-implement-strstr-java/
Analysis:
Be careful that if needle is empty, then no matter what haystack is, return 0.
If haystack is empty, then if needle is empty return 0, if needle is not empty return -1.
Edge cases:
"", ""
"", "a"
"a", ""
"a", "a" <-- if make "i < haystack.length() - needle.length()", this case will fail
*/
public class Solution {
// 1.Two Pointers
// public int strStr(String haystack, String needle) {
// if(haystack == null || needle == null ) return 0;
// if(needle.length() == 0) return 0;
// for(int i = 0; i <= haystack.length() - needle.length(); i++){
// int m = i;
// int j = 0;
// for(; j < needle.length(); j++){
// if(haystack.charAt(m) != needle.charAt(j)) break;
// m++;
// }
// if(j == needle.length()) return i;
// }
// return -1;
// }
// 2.Directly use String.indexOf(String). Perhaps we are not allowed to use it in interview.
public int strStr(String haystack, String needle) {
if(haystack == null || needle == null ) return 0;
if(needle.length() == 0) return 0;
return haystack.indexOf(needle);
}
}