Skip to content

Commit 9a89b2f

Browse files
authored
Update 0028-find-the-index-of-the-first-occurrence-in-a-string.kt
1 parent 22a35f0 commit 9a89b2f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Diff for: kotlin/0028-find-the-index-of-the-first-occurrence-in-a-string.kt

+41
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,47 @@ class Solution {
7575
}
7676
}
7777

78+
/*
79+
* Rabin-karp with proper hash. q should ideally be chosen as an high prime number to avoid no. of collisions.
80+
*/
81+
class Solution {
82+
fun strStr(haystack: String, needle: String): Int {
83+
if(needle.length > haystack.length) return -1
84+
85+
val q = 101
86+
val d = 256
87+
var needleHash = 0
88+
var hayHash = 0
89+
var hash = 1
90+
91+
for (i in 0..needle.lastIndex)
92+
hash = (hash * d) % q
93+
94+
for(i in 0..needle.lastIndex) {
95+
needleHash = (d * needleHash + (needle[i] - 'a')) % q
96+
hayHash = (d * hayHash + (haystack[i] - 'a')) % q
97+
}
98+
99+
for(i in 0..(haystack.length - needle.length)) {
100+
if(hayHash == needleHash) {
101+
for(j in 0..needle.lastIndex) {
102+
if(haystack[i + j] != needle[j])
103+
break
104+
if(j == needle.lastIndex)
105+
return i
106+
}
107+
}
108+
if(i == haystack.length - needle.length)
109+
break
110+
hayHash = (d * hayHash - ((haystack[i] - 'a') * hash) + (haystack[i + needle.length] - 'a')) % q
111+
if(hayHash < 0)
112+
hayHash += q
113+
}
114+
115+
return -1
116+
}
117+
}
118+
78119
/*
79120
* Using Trie to match pattern
80121
*/

0 commit comments

Comments
 (0)