Published:
Updated:

  • Reference
  • ๋ฌธ์ œ๋ฅผ ์ œ๋Œ€๋กœ ์•ˆ ์ฝ๊ณ  isdigit()๋กœ ํ•ด์„œ ์˜ค๋ž˜ ๊ฑธ๋ฆผ
    • ๋˜, ํˆฌํฌ์ธํ„ฐ ์•ˆ ์“ฐ๊ณ  ๋ฌธ์ž์—ด๋กœ ํ•˜๋‹ค๊ฐ€ ์•ˆ ๋ผ์„œ ๊ทธ๋ƒฅ ๋Œ์•„๊ฐ
  • ํˆฌํฌ์ธํ„ฐ๋กœ ํ’€ ๋•Œ๋งˆ๋‹ค ์งœ๋ฆฟํ•˜๋‹ค..


Solution

class Solution:
    def isPalindrome(self, s: str) -> bool:
        # 1. ์•ŒํŒŒ๋ฒณ ์ œ์™ธํ•œ ๋ชจ๋“  ๋ฌธ์ž ์ œ๊ฑฐ
        for w in s:
            # ์•ŒํŒŒ๋ฒณ์ด ์•„๋‹ˆ๋ผ๋ฉด ๊ทธ ๋ฌธ์ž๋Š” ๋‹ค ์—†์• ์ฃผ๊ธฐ
            if not w.isalpha() and not w.isdigit():
                s = s.replace(w, '')

        # 2. lowerCase
        s = s.lower()

        # 3. ๋’ค์ง‘์–ด๋„ ๊ฐ™์€์ง€ ๋น„๊ต (์‹คํŒจ)
        # 0P๋Š” False, a๋Š” True
        # if len(s) == 2:
        #     if s[0] == s[1]:
        #         return True
        #     else:
        #         return False
        #
        # if len(s) % 2 == 0:
        #     if s[:len(s) // 2 + 1] == s[len(s) // 2 + 1:][::-1]:
        #         return True
        #     else:
        #         return False
        # else:
        #     if s[:len(s) // 2] == s[len(s) // 2 + 1:][::-1]:
        #         return True
        #     else:
        #         return False

        # 3. ๋’ค์ง‘์–ด๋„ ๊ฐ™์€์ง€ ๋น„๊ต
        lt, rt = 0, len(s) - 1
        if len(s) % 2 == 0:
            for _ in range(len(s) // 2):
                if s[lt] != s[rt]:
                    return False
                lt += 1
                rt -= 1
        else:
            for _ in range(len(s) // 2 + 1):
                if s[lt] != s[rt]:
                    return False
                lt += 1
                rt -= 1

        return True


print(Solution().isPalindrome("A man, a plan, a canal: Panama"))

Leave a comment