File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -75,6 +75,47 @@ class Solution {
75
75
}
76
76
}
77
77
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
+
78
119
/*
79
120
* Using Trie to match pattern
80
121
*/
You can’t perform that action at this time.
0 commit comments