Given a string s, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: “aacecaaa”
Output: “aaacecaaa”
Example 2:
Input: “abcd”
Output: “dcbabcd”
func shortestPalindrome(s string) string {
lg := len(s)
for i := lg; i >= 0; i-- {
if isPalindrome(s[:i]) {
return Reverse(s[i:])+s
}
}
return s+s
}
func isPalindrome(s string) bool {
lg := len(s)
for i := 0; i < lg/2; i++ {
if s[i] != s[lg-1-i] {
return false
}
}
return true
}
func Reverse(s string) string {
size := len(s)
buf := make([]byte, size)
for start := 0; start < size; {
r, n := utf8.DecodeRuneInString(s[start:])
start += n
utf8.EncodeRune(buf[size-start:], r)
}
return string(buf)
}