LeetCode 솔루션 분류
[Easy - wk6 - Q1] 125. Valid Palindrome
본문
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.
관련자료
댓글 3
namsoo님의 댓글
- 익명
- 작성일
class Solution:
def isPalindrome(self, s: str) -> bool:
s2 = [x.lower() for x in s if x.isalpha() or x.isnumeric()]
left = 0
right = len(s2) - 1
while left < right:
if s2[left] != s2[right]:
return False
left += 1
right -= 1
return True
def isPalindrome(self, s: str) -> bool:
s2 = [x.lower() for x in s if x.isalpha() or x.isnumeric()]
left = 0
right = len(s2) - 1
while left < right:
if s2[left] != s2[right]:
return False
left += 1
right -= 1
return True
Coffee님의 댓글
- 익명
- 작성일
class Solution {
public boolean isPalindrome(String s) {
// two pointer
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;
}
}
학부유학생님의 댓글
- 익명
- 작성일
Runtime: 93 ms, faster than 19.64% of Python3 online submissions for Valid Palindrome.
Memory Usage: 14.7 MB, less than 43.06% of Python3 online submissions for Valid Palindrome.
Memory Usage: 14.7 MB, less than 43.06% of Python3 online submissions for Valid Palindrome.
class Solution:
def isPalindrome(self, s: str) -> bool:
new_s = ""
for char in s:
if ord('a') <= ord(char.lower()) <=ord('z'): new_s += char.lower()
elif char.isdigit(): new_s += char
return new_s[::-1] == new_s