Filter and Reverse
Intuition
A straightforward approach is to first build a cleaned version of the string containing only lowercase alphanumeric characters, then check if this cleaned string equals its reverse. This uses extra space to store the filtered string but is easy to understand and implement.
Algorithm
- Iterate through the string and keep only alphanumeric characters, converting each to lowercase.
- Build a new cleaned string from these characters.
- Reverse the cleaned string.
- Compare the cleaned string with its reversed version.
- Return true if they are equal, false otherwise.
O(n)SpaceO(n)Code (C++ · Java · Python · Go)
class Solution {
public:
bool isPalindrome(string s) {
string cleaned;
for (char c : s) {
if (isalnum(c)) {
cleaned += tolower(c);
}
}
string reversed = cleaned;
reverse(reversed.begin(), reversed.end());
return cleaned == reversed;
}
};class Solution {
public boolean isPalindrome(String s) {
StringBuilder cleaned = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
cleaned.append(Character.toLowerCase(c));
}
}
String forward = cleaned.toString();
String reversed = cleaned.reverse().toString();
return forward.equals(reversed);
}
}def isPalindrome(s: str) -> bool:
cleaned = "".join(c.lower() for c in s if c.isalnum())
return cleaned == cleaned[::-1]import (
"strings"
"unicode"
)
func isPalindrome(s string) bool {
var cleaned []rune
for _, c := range s {
if unicode.IsLetter(c) || unicode.IsDigit(c) {
cleaned = append(cleaned, unicode.ToLower(c))
}
}
reversed := make([]rune, len(cleaned))
for i, c := range cleaned {
reversed[len(cleaned)-1-i] = c
}
return string(cleaned) == string(reversed)
}