forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementStrstr.java
More file actions
33 lines (32 loc) · 1.04 KB
/
ImplementStrstr.java
File metadata and controls
33 lines (32 loc) · 1.04 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
//If use startWith, it's easy
public class Solution {
public String strStr(String haystack, String needle) {
// Start typing your Java solution below
// DO NOT write main() function
if(needle.length() == 0)
return haystack;
for(int i = 0; i < haystack.length(); ++i){
if(haystack.substring(i).startsWith(needle))
return haystack.substring(i);
}
return null;
}
}
//without using startsWith()
public class Solution {
public String strStr(String haystack, String needle) {
// Start typing your Java solution below
// DO NOT write main() function
if(needle.length() == 0)
return haystack;
for(int i = 0; i < haystack.length() - needle.length() + 1; ++i){
for(int j = 0; j < needle.length(); ++j){
if(haystack.charAt(i + j) != needle.charAt(j))
break;
if(j == needle.length() - 1)
return haystack.substring(i);
}
}
return null;
}
}