๊ฐœ๋ฐœ/๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode] 125. Valid Palindrome ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 10. 23. 23:34

 

๋ฌธ์ œ ๋งํฌ

https://leetcode.com/problems/valid-palindrome/

 

Valid Palindrome - LeetCode

Can you solve this real interview question? 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 cha

leetcode.com

 

neetcode ์ƒ์—์„œ two pointers๋กœ ๋ถ„๋ฅ˜๋˜์–ด ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค. 

 

1์ฐจ ํ’€์ด

๋ฌธ์ œ๋ฅผ ์ž˜ ์ฝ์–ด๋ณด๋ฉด, removing all non-alphanumeric characters ๋ผ๋Š” ๋ง์ด ๋ณด์ธ๋‹ค. 

์•ŒํŒŒ๋ฒณ์ด ์•„๋‹Œ ๋ฌธ์ž๋“ค์„ ๊ฑธ๋Ÿฌ์ค˜์•ผ ํ•œ๋‹ค. ์ด ๋ถ€๋ถ„์€ isalnum ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด์„œ ํ•ด๊ฒฐํ–ˆ๋‹ค. 

์ฐธ๊ณ ๋กœ, isalnum ์€ ์•ŒํŒŒ๋ฒณ๊ณผ ์ˆซ์ž๋ฅผ ํ—ˆ์šฉํ•˜๊ณ , isalpha๋Š” ์•ŒํŒŒ๋ฒณ๋งŒ ํ—ˆ์šฉํ•˜๋Š”๋ฐ, ๋ฌธ์ œ ์ƒ์—์„œ๋Š” ์•ŒํŒŒ๋ฒณ๊ณผ ์ˆซ์ž๋ฅผ ํ—ˆ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— isalnum์„ ์‚ฌ์šฉํ•ด์•ผ ํ–ˆ๋‹ค. 

- isalnum : https://zetawiki.com/wiki/%ED%8C%8C%EC%9D%B4%EC%8D%AC_isalnum()

- isalpha : https://zetawiki.com/wiki/%ED%8C%8C%EC%9D%B4%EC%8D%AC_isalpha()

class Solution(object):
    def isPalindrome(self, s):
        
        testString = [] 
        for c in s:
            if c.isalnum():
                testString.append(c.lower())
        
        for i,c in enumerate(testString):
            if c != testString[-i-1]:
                return False
        
        return True

 

 

2์ฐจ ํ’€์ด (ํ•ด์„ค ์ฐธ๊ณ )

https://www.youtube.com/watch?v=jJXJ16kPFWg

์ฒซ๋ฒˆ์งธ๋กœ ํ•ด์„ค๊ฐ•์ขŒ์—์„œ ์ œ๊ณตํ•ด์ฃผ๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. 

๋‚ด ์ฒซ๋ฒˆ์งธ ํ’€์ด์™€ ์œ ์‚ฌํ•˜์ง€๋งŒ, array ๋Œ€์‹  ์ŠคํŠธ๋ง์œผ๋กœ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. 

์กฐ๊ธˆ ๊ด€์‹ฌ์žˆ๊ฒŒ ๋ณผ๋งŒํ•œ ๋ถ€๋ถ„์€ newStr == newStr[::-1] ํ†ตํ•ด์„œ array ๋ฐฐ์—ด ๊ฐ’ ๊ฒ€์‚ฌ๋ฅผ ํ•œ ๊ฒƒ.  ํŒŒ์ด์ฌ์—์„œ๋Š” array ์ž์ฒด๋ฅผ ๋น„๊ต๊ฐ€๋Šฅํ•˜๋‹ค. 

 newStr = "" 
    for c in s:
        if c.isalnum():
            newStr += c.lower()
    return newStr == newStr[::-1]

 

๋‹ค์Œ์œผ๋กœ ์ œ๊ณตํ•ด์ฃผ๋Š” ๋ฐฉ๋ฒ•์€ ์ถ”๊ฐ€์ ์ธ ๋ฉ”๋ชจ๋ฆฌ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ํ‘ธ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฐฉ๋ฒ•์ด๋‹ค. 

while๋ฌธ ์•ˆ์— while ๋ฌธ์„ ์“ฐ๋Š” ๋ญ”๊ฐ€ ์ผํ• ๋•Œ ์“ฐ๋ฉด ์•ˆ๋ผ๋Š” ๋ฐฉ์‹์ด๋ผ, ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋”๋ผ๋„ ์†์ด ์•ˆ๊ฐ„๋‹ค. 

ํ•˜์ง€๋งŒ, ๋‚ด๊ฐ€ ์ œ์ถœํ–ˆ๋˜ ํ’€์ด ์ค‘์—์„œ, ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ๊ฐ€์žฅ ์ ๊ฒŒ ์“ฐ์ด๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค. 

  l, r = 0, len(s) -1
        while l < r:
            while l < r and not self.alphaNum(s[l]):
                l += 1
            while r > l and not self.alphaNum(s[r]):
                r -= 1 
            
            if s[l].lower() != s[r].lower():
                return False      
            
            l, r = l + 1, r - 1
        
        return True
    
    
    def alphaNum(self, c):
        return (
            ord('A') <= ord(c) <= ord('Z') or
            ord('a') <= ord(c) <= ord('z') or
            ord('0') <= ord(c) <= ord('9') 
        )

 

 

๋ฐ˜์‘ํ˜•