-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq028_ImplementStrStr.java
More file actions
43 lines (35 loc) · 974 Bytes
/
q028_ImplementStrStr.java
File metadata and controls
43 lines (35 loc) · 974 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
32
33
34
35
36
37
38
39
40
41
42
43
package leetcode_algorithm;
/**
*
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*/
public class q028_ImplementStrStr {
public static void main(String[] args) {
System.out.println(strStr2("sdrvseew143" , "rv"));
}
/**
* 解法1 个人解法
* @param haystack
* @param needle
* @return
*/
public static int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
/**
* 解法2 推荐解法
* @param haystack
* @param needle
* @return
*/
public static int strStr2(String haystack, String needle) {
for(int i = 0 ;;i++) {
for(int j = 0;;j++) {
if(j == needle.length()) return i;
if(i + j == haystack.length()) return -1;
if(needle.charAt(j) != haystack.charAt(i + j)) break;
}
}
}
}