Skip to content

Commit

Permalink
feat: Manacher's algorithm (#408)
Browse files Browse the repository at this point in the history
  • Loading branch information
i-redbyte authored Oct 28, 2021
1 parent 2485670 commit e192812
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
63 changes: 63 additions & 0 deletions strings/manacher/longestpalindrome.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// longestpalindrome.go
// description: Manacher's algorithm (Longest palindromic substring)
// details:
// An algorithm with linear running time that allows you to get compressed information about all palindromic substrings of a given string. - [Manacher's algorithm](https://en.wikipedia.org/wiki/Longest_palindromic_substring)
// author(s) [red_byte](https://github.com/i-redbyte)
// see longestpalindrome_test.go

package manacher

import (
"github.com/TheAlgorithms/Go/math/min"
"strings"
)

func makeBoundaries(s string) string {
var result strings.Builder
result.WriteRune('#')
for _, ch := range s {
if ch != ' ' { //ignore space as palindrome character
result.WriteRune(ch)
}
result.WriteRune('#')
}
return result.String()
}

func nextBoundary(s string) string {
var result strings.Builder
for _, ch := range s {
if ch != '#' {
result.WriteRune(ch)
}
}
return result.String()
}

func LongestPalindrome(s string) string {
boundaries := makeBoundaries(s)
b := make([]int, len(boundaries))
k := 0
index := 0
maxLen := 0
maxCenterSize := 0
for i := range b {
if i < k {
b[i] = min.Int(b[2*index-i], k-i)
} else {
b[i] = 1
}
for i-b[i] >= 0 && i+b[i] < len(boundaries) && boundaries[i-b[i]] == boundaries[i+b[i]] {
b[i] += 1
}
if maxLen < b[i]-1 {
maxLen = b[i] - 1
maxCenterSize = i
}
if b[i]+i-1 > k {
k = b[i] + i - 1
index = i
}
}
return nextBoundary(boundaries[maxCenterSize-maxLen : maxCenterSize+maxLen])
}
38 changes: 38 additions & 0 deletions strings/manacher/longestpalindrome_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// longestpalindrome_test.go
// description: Manacher's algorithm (Longest palindromic substring)
// author(s) [red_byte](https://github.com/i-redbyte)
// see longestpalindrome.go

package manacher

import "testing"

func getTests() []struct {
s string
result string
} {
var tests = []struct {
s string
result string
}{
{"olokazakabba", "kazak"},
{"abaacakkkkk", "kkkkk"},
{"qqqq C++ groovy mom pooop", "pooop"},
{"CCCPCCC @@@ hello", "CCCPCCC"},
{"goog gogogogogog -go- gogogogo ", "gogogogogog"},
}
return tests
}

func TestLongestPalindrome(t *testing.T) {
tests := getTests()
for _, tv := range tests {
t.Run(tv.s, func(t *testing.T) {
result := LongestPalindrome(tv.s)
t.Log(tv.s, " ", result)
if result != tv.result {
t.Errorf("Wrong result! Expected:%s, returned:%s ", tv.result, result)
}
})
}
}

0 comments on commit e192812

Please sign in to comment.