https://leetcode.com/problems/valid-palindrome/description/
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string s, return true__ if it is a **palindrome**, or __false__ otherwise__.
Example 1: Input: s = “A man, a plan, a canal: Panama” Output: true Explanation: “amanaplanacanalpanama” is a palindrome. Example 2: Input: s = “race a car” Output: false Explanation: “raceacar” is not a palindrome. Example 3: Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.
- code
class Solution {
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j){
if (!Character.isLetterOrDigit(s.charAt(i))){
i++;
continue;
}
if (!Character.isLetterOrDigit(s.charAt(j))){
j--;
continue;
}
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))){
return false;
}
i++;
j--;
}
return true;
}
}
- code
class Solution {
public boolean isPalindrome(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
while (i < j && !Character.isLetterOrDigit(s.charAt(i))) {
i++;
}
while (i < j && !Character.isLetterOrDigit(s.charAt(j))) {
j--;
}
if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j)))
return false;
}
return true;
}
}
- code
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s)-1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return False
i += 1
j -= 1
return True
- code
class Solution:
def isPalindrome(self, s: str) -> bool:
if s == '':
return True
final = re.sub(r'\W+', '', s).lower()
return final == final[::-1]