Leetcode Problem
Valid Palindrome
Given a string s
, return true
if it is a palindrome, otherwise return false
. A palindrome is a string that reads the same forward and backward. It is also case-insensitive and ignores all non-alphanumeric characters.
Example 1:
Input: s = "Was it a car or a cat I saw?"
Output: true
Explanation: After considering only alphanumerical characters we have "wasitacaroracatisaw"
, which is a palindrome.
Example 2:
Input: s = "tab a cat"
Output: false
Explanation: "tabacat"
is not a palindrome.
Constraints:
1 <= s.length <= 1000
s
is made up of only printable ASCII characters.
Golang Solution:
func isPalindrome(s string) bool {
start := 0
end := len(s) - 1
runes := []rune(s)
for start < end {
if !(unicode.IsLetter(runes[start]) || unicode.IsDigit(runes[start])) {
start++
continue
}
if !(unicode.IsLetter(runes[end]) || unicode.IsDigit(runes[end])) {
end--
continue
}
if unicode.ToLower(runes[start]) != unicode.ToLower(runes[end]) {
return false
}
start++
end--
}
return true
}
Failed Attempt:
The initial attempt to solve the problem was unsuccessful. The code did not handle all edge cases, particularly when the string contained special characters or spaces. The logic for checking the characters was not robust enough to account for these scenarios.
func isPalindrome(s string) bool {
start := 0
end := len(s) - 1
runes := []rune(s)
for start < end {
if !unicode.IsLetter(runes[start]) {
start++
continue
}
if !unicode.IsLetter(runes[end]) {
end--
continue
}
if unicode.ToLower(runes[start]) != unicode.ToLower(runes[end]) {
return false
}
start++
end--
}
return true
}
The above code failed to consider digits, leading to incorrect results for certain inputs.
Failed Test Case:
Input: s = "0P"
Output: true
Expected: false