File tree Expand file tree Collapse file tree 1 file changed +59
-1
lines changed
solution/3300-3399/3303.Find the Occurrence of First Almost Equal Substring Expand file tree Collapse file tree 1 file changed +59
-1
lines changed Original file line number Diff line number Diff line change @@ -108,7 +108,65 @@ A <strong>substring</strong> is a contiguous <b>non-empty</b> sequence of charac
108
108
#### Go
109
109
110
110
``` go
111
-
111
+ func zAlgorithm (s string ) []int {
112
+ n := len (s)
113
+ z := make ([]int , n)
114
+ l , r := -1 , -1
115
+ for i := 1 ; i < n; i++ {
116
+ if i > r {
117
+ l, r = i, i
118
+ for r < n && s[r-l] == s[r] {
119
+ r++
120
+ }
121
+ z[i] = r - l
122
+ r--
123
+ } else {
124
+ k := i - l
125
+ if z[k] < r-i+1 {
126
+ z[i] = z[k]
127
+ } else {
128
+ l = i
129
+ for r < n && s[r-l] == s[r] {
130
+ r++
131
+ }
132
+ z[i] = r - l
133
+ r--
134
+ }
135
+ }
136
+ }
137
+ z[0 ] = n
138
+ return z
139
+ }
140
+
141
+ func minStartingIndex (s string , pattern string ) int {
142
+ n , m := len (s), len (pattern)
143
+ z1 := zAlgorithm (pattern + s)
144
+ z2 := zAlgorithm (reverse (pattern) + reverse (s))
145
+ for i := 0 ; i < n; i++ {
146
+ if i+m > n {
147
+ break
148
+ }
149
+ c1 := z1[i+m]
150
+ if c1 >= m {
151
+ return i
152
+ }
153
+ j := i + m - 1
154
+ c2 := z2[n-j-1 +m]
155
+ if c1+c2 == m-1 {
156
+ return i
157
+ }
158
+ }
159
+ return -1
160
+ }
161
+
162
+ func reverse (s string ) string {
163
+ n := len (s)
164
+ runes := []rune (s)
165
+ for i := 0 ; i < n/2 ; i++ {
166
+ runes[i], runes[n-i-1 ] = runes[n-i-1 ], runes[i]
167
+ }
168
+ return string (runes)
169
+ }
112
170
```
113
171
114
172
<!-- tabs:end -->
You can’t perform that action at this time.
0 commit comments