File tree Expand file tree Collapse file tree 2 files changed +75
-1
lines changed
SubstringwithConcatenationofAllWords Expand file tree Collapse file tree 2 files changed +75
-1
lines changed Original file line number Diff line number Diff line change
1
+ package ImplementstrStr ;
2
+
3
+ /**
4
+ * User: Danyang
5
+ * Date: 1/29/2015
6
+ * Time: 19:26
7
+ *
8
+ * Implement strStr().
9
+
10
+ Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
11
+ */
12
+ public class Solution {
13
+ /**
14
+ * KMP
15
+ *
16
+ * Notice:
17
+ * 1. build a table of the length of matched prefix_suffix - PREFIX SUFFIX LENGTH TABLE
18
+ * 2. test case "mississippi", "issip"; "redoredoreo", "redoreo"
19
+ * 3. S[i+j]
20
+ * @param haystack
21
+ * @param needle
22
+ * @return
23
+ */
24
+ public int strStr (String haystack , String needle ) {
25
+ if (haystack .length ()<needle .length ())
26
+ return -1 ;
27
+ if (needle .length ()<=1 )
28
+ return haystack .indexOf (needle );
29
+
30
+ char [] S = haystack .toCharArray ();
31
+ char [] W = needle .toCharArray ();
32
+ // build prefix_suffix_length_table
33
+ int [] T = new int [W .length +1 ];
34
+ T [0 ] = -1 ;
35
+ T [1 ] = 0 ;
36
+ int i = 0 ;
37
+ int j ;
38
+ for (j =1 ; j <W .length ; ) {
39
+ if (W [i ]==W [j ]) {
40
+ T [j +1 ] = i +1 ;
41
+ i ++;
42
+ j ++;
43
+ }
44
+ else if (i !=0 ) { // reredo...rerereply
45
+ i = T [i ];
46
+ }
47
+ else {
48
+ T [j +1 ] = 0 ;
49
+ j ++;
50
+ }
51
+ }
52
+
53
+ // search
54
+ i = 0 ;
55
+ j = 0 ;
56
+ while (i +j <S .length ) {
57
+ if (S [i +j ]==W [j ]) {
58
+ j ++;
59
+ if (j ==W .length )
60
+ return i ;
61
+ }
62
+ else {
63
+ if (T [j ]!=-1 ) {
64
+ i = i +j -T [j ];
65
+ j = T [j ];
66
+ }
67
+ else {
68
+ i += 1 ;
69
+ j = 0 ;
70
+ }
71
+ }
72
+ }
73
+ return -1 ;
74
+ }
75
+ }
Original file line number Diff line number Diff line change @@ -57,7 +57,6 @@ public List<Integer> findSubstring(String S, String[] L) {
57
57
workingWin .clear ();
58
58
win_e = -1 ;
59
59
Lmap = new HashMap <>(Lmap_origin );
60
- continue ;
61
60
}
62
61
}
63
62
You can’t perform that action at this time.
0 commit comments