-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28.implement-strstr.java
More file actions
41 lines (32 loc) · 1.15 KB
/
Copy path28.implement-strstr.java
File metadata and controls
41 lines (32 loc) · 1.15 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
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length() == 0)
return 0;
if(needle.length() > haystack.length())
return -1;
Queue<int[]> q = new LinkedList<int[]>();
for(int i=0;i<haystack.length()-needle.length()+1;i++){
if(needle.charAt(0) == haystack.charAt(i))
q.offer(new int[]{0,i});
}
// System.out.println(q);
// int p = 0;
while(!q.isEmpty()){
int sz = q.size();
while(sz>0){
int[] currind = q.poll();
int k = currind[1];
int ned = currind[0];
if(k<haystack.length() && ned<needle.length() && haystack.charAt(k) == needle.charAt(ned)){
k++;
ned++;
q.offer(new int[]{ned, k});
}
if(ned == needle.length())
return k-ned;
sz--;
}
}
return -1;
}
}