-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_strStr.java
More file actions
32 lines (31 loc) · 1.01 KB
/
Copy pathImplement_strStr.java
File metadata and controls
32 lines (31 loc) · 1.01 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
/**
* Implement strStr()
*
* Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
*
* @author Josh Luo
*
* For each char in haystack, match the whole needle string. O(m * n).
*/
public class Implement_strStr {
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;
for (int i = 0; i < haystack.length(); i++) {
if ((haystack.length() - i) < needle.length())
break;
int j = 0;
while (j < needle.length()) {
if (haystack.charAt(i + j) != needle.charAt(j))
break;
j++;
}
if (j == needle.length())
return haystack.substring(i);
}
return null;
}
}