Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9a89b2f

Browse files
authored
Update 0028-find-the-index-of-the-first-occurrence-in-a-string.kt
1 parent22a35f0 commit9a89b2f

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎kotlin/0028-find-the-index-of-the-first-occurrence-in-a-string.kt

Lines changed: 41 additions & 0 deletions
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+
classSolution {
82+
funstrStr(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 (iin0..needle.lastIndex)
92+
hash= (hash* d)% q
93+
94+
for(iin0..needle.lastIndex) {
95+
needleHash= (d* needleHash+ (needle[i]-'a'))% q
96+
hayHash= (d* hayHash+ (haystack[i]-'a'))% q
97+
}
98+
99+
for(iin0..(haystack.length- needle.length)) {
100+
if(hayHash== needleHash) {
101+
for(jin0..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)

[8]ページ先頭

©2009-2025 Movatter.jp