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
๋‹คํ–ˆ๋‹ค