-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementstrStr.java
More file actions
58 lines (54 loc) · 1.36 KB
/
ImplementstrStr.java
File metadata and controls
58 lines (54 loc) · 1.36 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package easy;
/**
* Implement strStr().
* Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*
* Created by kaming on 2018/7/24.
*/
public class ImplementstrStr {
/**
* Example 1:
*
* Input: haystack = "hello", needle = "ll"
* Output: 2
* Example 2:
*
* Input: haystack = "aaaaa", needle = "bba"
* Output: -1
*/
public static void main(String[] args){
int exp1 = strStr("hello,","ll");
System.out.println(exp1);
int exp2 = strStr("aaaaa,","bba");
System.out.println(exp2);
}
private static int strStr(String haystack, String needle) {
if (haystack == null || needle == null) {
return 0;
}
int n = haystack.length();
int m = needle.length();
if(m == 0){
return 0;
}
if(n == 0){
return -1;
}
if (m > n) {
return -1;
}
for (int i = 0; i <= n - m; i++) {
boolean successFlag = true;
for (int j = 0; j < m; j++) {
if (haystack.charAt(i+j) != needle.charAt(j)) {
successFlag = false;
break;
}
}
if (successFlag){
return i;
}
}
return -1;
}
}