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.
쉽다.
Python엔 charcter을 alpha / numberic 구분하는 method가 많아서 naive하게 바로 접근이 가능하다.
1. Python
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
temp = ""
for i in range(len(s)):
if s[i].isalpha() or s[i].isnumeric():
temp += s[i]
# if not temp : return True
# check palidrome
h = 0
t = len(temp)-1
while h <= t :
if temp[h] != temp[t] : return False
h+=1
t-=1
return True
하나 알게 된 건, string S가 있을 때, S[: : -1]하면 S가 거꾸로 reverse 된 놈이 나타난다.
즉, s = s[: : -1]로도 palidrome을 check할 수 있다는 것!
2. C
C -> ctype.h , C++ -> cctype 이라는 header에 각각 isalnum,isalph ,tolower 등의 편리한 method들이 저장되어 있다.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
bool isPalindrome(char* s) {
int n = strlen(s);
int h = 0;
int t = n-1;
while(h<=t){
if(!isalnum(s[h])){
h++;
continue;
}
else if(!isalnum(s[t])){
t--;
continue;
}
else if(tolower(s[h])!=tolower(s[t])) return false;
else{
h++;
t--;
}
}
return true;
}