Skip to content

Instantly share code, notes, and snippets.

@twfarland
Last active December 18, 2015 14:29
Show Gist options
  • Save twfarland/5797705 to your computer and use it in GitHub Desktop.
Save twfarland/5797705 to your computer and use it in GitHub Desktop.
longest palindrome
package main
import (
"fmt"
"io/ioutil"
)
// " \t\r\n"
var spaces = map[byte]bool{ 32: true, 9: true, 10: true, 13: true }
func longestPalindrome(text []byte) ([]byte, int, int) {
textlen := len(text)
maxlen := 0
maxlow := 0
maxhigh := 0
low := 0
high := 0
var current byte
var previous byte
for i := range text {
// lowercase char
if text[i] > 64 && text[i] < 91 { text[i] += 32 }
// Handle both odd and even-length palindromes
for j := i; j < i + 2 && j < textlen; j ++ {
low = i
high = j
// Expand while the subregion is a valid palindrome
for text[low] == text[high] {
// discount multiple spaces
current = text[low]
if spaces[current] && spaces[previous] { break }
// If longest found, update
if high - low > maxlen {
maxlow = low
maxhigh = high
maxlen = maxhigh - maxlow
}
// update prev
previous = current
// expand indexes
if low > 0 { low -- } else { break }
if high < textlen - 1 { high ++ } else { break }
}
}
}
maxhigh ++; if maxhigh > textlen { maxhigh = textlen }
return text[maxlow : maxhigh], maxlow, maxhigh
}
func main() {
text, _ := ioutil.ReadFile("war_and_peace.txt")
str, _, _ := longestPalindrome(text)
fmt.Println(string(str))
fmt.Println(str)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment