Problem:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
-Summary-
1. Modified the given s string to remove all white spaces and special characters.
2. Compare the beginning and the end until it reaches out to the middle.
3. If not any character that is not matching, return False. After loop return True, as it is Palindrome.
이번 문제를 풀면서 아래의 함수들을 다시 공부하게 되고 새롭게 알게 되었다. 그리고 for loop one line statement 도 계속 쓰면서 익숙해지는것 같다.
'seperator'.join(input_string) #join method
'''
The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
https://www.w3schools.com/python/ref_string_join.asp
'''
input_string.isalnum() #isalnum method
'''
Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise.
A character c is alphanumeric if one of the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), or c.isnumeric().
https://docs.python.org/3/library/stdtypes.html#str.isalnum
'''
-Deque 를 이용한 문제풀이-
class Solution:
def isPalindrome(self, s: str) -> bool:
strs = collections.deque()
for char in s:
if char.isalnum():
strs.append(char.lower())
while len(strs) > 1:
if strs.popleft() != strs.pop():
return False
return True
-Regex 를 이용한 문제풀이-
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
s = re.sub('[^a-z0-9]','',s)
return s == s[::-1]
모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]
'LeetCode > Top Interview Q. - Easy' 카테고리의 다른 글
LeetCode. Implement strStr() [String] (0) | 2020.06.02 |
---|---|
LeetCode. String to Integer (atoi) [String] (0) | 2020.06.02 |
LeetCode 242. Valid Anagram (0) | 2020.05.25 |
LeetCode 387. First Unique Character in a String (0) | 2020.05.25 |
LeetCode 7. Reverse Integer (0) | 2020.05.25 |
댓글