Solution for String pattern Matching with three algoritms#1467
Solution for String pattern Matching with three algoritms#1467RezaSi merged 2 commits intoRezaSi:mainfrom
Conversation
WalkthroughAdds a new Go source file providing three pattern-matching implementations (Naive, KMP, Rabin–Karp) that operate on rune slices, return starting indices of matches, and include a main with test cases; functions handle empty inputs and pattern-longer-than-text edge cases. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
challenge-23/submissions/PopovMarko/solution-template.go (2)
44-55: Consider extracting shared preprocessing into a small helper.Rune conversion and guard checks are duplicated across all three algorithms; factoring this once would reduce maintenance drift.
Also applies to: 83-94, 149-160
143-145: Consider usingint64for rolling-hash arithmetic to support 32-bit platforms.The rolling-hash computation at lines 28, 33–34, and 52 uses untyped integer constants (
base=256, mod=101) withint-typed variables. On 32-bit architectures, expressions likebase*(textHash-int(rText[i])*h)can overflow and corrupt matches. No 32-bit targets are currently tested in CI (Go 1.25.0 default is 64-bit), but usingint64improves portability.🔧 Suggested fix
func RabinKarpSearch(text, pattern string) []int { - const base = 256 - const mod = 101 // prime number + const base int64 = 256 + const mod int64 = 101 // prime number res := []int{} rText := []rune(text) rPattern := []rune(pattern) lenPattern := len(rPattern) lenText := len(rText) if text == "" || pattern == "" || lenPattern > lenText { return []int{} } - var patternHash, textHash, h int + var patternHash, textHash, h int64 h = 1 for i := 0; i < lenPattern-1; i++ { h = (h * base) % mod } for i := range lenPattern { - patternHash = (base*patternHash + int(rPattern[i])) % mod - textHash = (base*textHash + int(rText[i])) % mod + patternHash = (base*patternHash + int64(rPattern[i])) % mod + textHash = (base*textHash + int64(rText[i])) % mod } for i := 0; i <= lenText-lenPattern; i++ { if patternHash == textHash { match := true for j := range lenPattern { if rText[i+j] != rPattern[j] { match = false break } } if match { res = append(res, i) } } if i < lenText-lenPattern { - textHash = (base*(textHash-int(rText[i])*h) + int(rText[i+lenPattern])) % mod + textHash = (base*(textHash-int64(rText[i])*h) + int64(rText[i+lenPattern])) % mod if textHash < 0 { textHash += mod } } } return res }
Naive, KMP, RabinKarp implement three algoritms