728x90
LeetCode 125 Valid Palindrome
Palindrome : ๋์๋ฌธ์ ๊ตฌ๋ถ ์์ด ์ข์ฐ๊ฐ ๋์นญ์ธ ๋ฌธ์์ด
1. isalnum : ๋ฌธ์ ํ๋ณ ํ ์๋ฌธ์ ๋ณํ
test = 'is a car ; rac a si'
c_string = []
for s in test:
if s.isalnum(): # ๋ฌธ์์ธ์ง ํ๋ณ
c_string.append(s.lower()) # ์๋ฌธ์๋ก ๋ณํ
# c_string # ['i', 's', 'a', 'c', 'a', 'r', 'r', 'a', 'c', 'a', 's', 'i']
2. loop๋ก ์ฒซ๋ฒ์งธ ๋ง์ง๋ง ๋ฌธ์์ด ๋น๊ต ํ pop
while len(c_string) > 1:
if c_string.pop(0) != c_string.pop():
break
#c_string # = [] True
Result : 221ms Memory: 19.5MB
3. ์ฒ์ ๋์ถํ ๋ต์
class Solution:
def isPalindrome(self, s: str) -> bool:
p = []
for i in range(len(s)):
if s[i].isalnum():
p.append(s[i].lower())
p = ''.join(p)
k = len(p) // 2
if p[:k] == ''.join([p[len(p)-i-1] for i in range(k)]):
return True
else:
return False
Result : 63ms Memory: 19.3
4. ๊ฐ์ ๋ต์ (๋ฐ์ฝ ์๋ฃํ์ ์ด์ฉํ ์ต์ ํ)
- pop(0)์ ๋ณต์ก๋๊ฐ O(n), popleft()๋ O(1)๋ก ๋ฆฌ์คํธ ์ ๊ทผ๋ณด๋ค 5๋ฐฐ ๋น ๋ฅด๋ค.
class Solution:
def isPalindrome(self, s: str) -> bool:
strs: Deque = collections.deque()
for i in s:
if i.isalnum():
strs.append(i.lower())
while len(strs) > 1:
if strs.popleft() != strs.pop():
return False
return True
Result : 31ms Memory: 19.3
* python-markdown์ ์ด์ฉํ ์๋ code review markdown ์์ฑ๊ธฐ
๋ฐ์ํ
'๐ข One step' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
LeetCode - Time complexity ์๊ฐ ๋ณต์ก๋ (0) | 2023.03.02 |
---|---|
[leetcode-819] Most Common Word (0) | 2023.03.02 |
[leetcode-937] Reorder_Data_in_LogFile (0) | 2023.03.01 |
[leetcode-344] ReverseString (0) | 2023.02.27 |
[leetcode-125] Palindrome + Slicing (0) | 2023.02.27 |