Longest Palindromic Substring

package mainimport "fmt"func main() {
str := "abcxxyyxxdef"
palindrome := ""
for i := 1; i < len(str)-1; i++ {
if tmpPalindrome := getPalindromicSubstr(str, i, true); tmpPalindrome != "" && len(tmpPalindrome) > len(palindrome) {
palindrome = tmpPalindrome
}
if tmpPalindrome := getPalindromicSubstr(str, i, false); tmpPalindrome != "" && len(tmpPalindrome) > len(palindrome) {
palindrome = tmpPalindrome
}
}
if palindrome == ""{
palindrome = str[:1]
}
fmt.Println("Longest palindromic substring : ", palindrome)
}
func getPalindromicSubstr(str string, idx int, odd bool) string {
lenStr := len(str)
palindrome := ""
var i, j int
if odd {
i = idx - 1
j = idx + 1
} else {
i = idx - 1
j = idx
}
for i >= 0 && j < lenStr {
if tmp, ok := isPalindrome(str, i, j); ok {
palindrome = tmp
i--
j++
} else {
return palindrome
}
}
return palindrome
}
func isPalindrome(str string, idxStart, idxEnd int) (string, bool) {
subStr := str[idxStart : idxEnd+1]
lastIdx := len(subStr) - 1
for i := 0; i < lastIdx/2 && i < (lastIdx-i); i++ {
if subStr[i] != subStr[lastIdx-i] {
return "", false
}
}
return subStr, true
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store