I have an ASCII-only string which is either already a palindrome, or else can be made a palindrome by removing one character. I need to determine whether it's already a palindrome, and if not, I need to find the index of the character that would need to be removed. For example, if the string is 'aaba'
, then it can be made into the palindrome 'aba'
by removing the first character, so I need to return 0
.
I have working code, but I am wondering if it is possible to make it faster, because I need to work with many long strings.
Here is my code:
package main
import (
"fmt"
)
func Palindrome(s string) bool {
var l int = len(s)
for i := 0; i < l / 2; i++ {
if s[i] != s[l - 1 - i] {
return false;
}
}
return true
}
func RemoveChar(s string, idx int) string {
return s[0:idx-1] + s[idx:len(s)]
}
func findIdx(s string) int {
if Palindrome(s) {
return -1
}
for i := 0; i < len(s); i++ {
if Palindrome(RemoveChar(s, i + 1)) {
return i
}
}
return -2
}
func main() {
var s string = "aabaab"
fmt.Println(findIdx(s))
}