forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path028ImplementStrStr.java
More file actions
42 lines (35 loc) · 1.01 KB
/
028ImplementStrStr.java
File metadata and controls
42 lines (35 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
33
34
35
36
37
38
39
40
41
42
// Author: Li Long, [email protected]
// Date: Apr 18, 2014
// Source: http://oj.leetcode.com/problems/implement-strstr/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/23655843
// Implement strStr().
// Returns a pointer to the first occurrence of needle in haystack,
// or null if needle is not part of haystack.
public class ImplementStrStr {
public String strStr(String haystack, String needle) {
if (needle != null && needle.isEmpty()) {
return haystack;
}
int len1 = haystack.length();
int len2 = needle.length();
if (len1 < len2) {
return null;
}
for (int i = 0; i <= len1 - len2; ++i) {
int j = 0;
int k = i;
while (j < len2 && needle.charAt(j) == haystack.charAt(k)) {
j++;
k++;
}
if (j == len2) {
return haystack.substring(i);
}
}
return null;
}
public static void main(String[] args) {
ImplementStrStr slt = new ImplementStrStr();
System.out.println(slt.strStr("abcdabc", "d"));
}
}