-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_strStr.java
More file actions
31 lines (26 loc) · 908 Bytes
/
Implement_strStr.java
File metadata and controls
31 lines (26 loc) · 908 Bytes
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
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if
needle is not part of haystack.
public class Solution {
public String strStr(String haystack, String needle) {
// Start typing your Java solution below
// DO NOT write main() function
assert(haystack!=null && needle!=null);
if(needle.length()==0)
return haystack;
int i = 0;
while(i<haystack.length()) {
if(haystack.length()-i < needle.length())
break;
if(haystack.charAt(i)==needle.charAt(0)) {
int j = i;
while(j-i<needle.length() && haystack.charAt(j)==needle.charAt(j-i))
j++;
if(j-i==needle.length())
return haystack.substring(i);
}
i++;
}
return null;
}
}