Valid Palindrome
Problem
- Given a string s, return true if it is a palindrome, or false otherwise.
Approach
- 1. Clean up the string by converting to lower case then removing whitespace/checking the rune values.
- 2. Compare the left and right side moving inward with two pointers
Edge Cases
- ' ' -> true
Reflections
This was a horrendous approach. I need to study up on runes, ASCII, and strings mutation.
Go Solution
import "strings"
func isPalindrome(s string) bool {
s = formatString(s)
fmt.Print(s)
left, right := 0, len(s) - 1
for left <= right {
leftLetter, rightLetter:= s[left], s[right]
if leftLetter != rightLetter {
return false
}
left++
right--
}
return true
}
func formatString(s string) string {
s = strings.ToLower(s)
s = strings.TrimSpace(s)
res:= ""
for _, letter := range s {
if (letter >= 'a' && letter <= 'z') || (letter >= '0' && letter <= '9') {
res += string(letter)
}
}
return res
};Performance
- Runtime beats: 10%
- Memory beats: 10%