Valid Palindrome

๋ฌธ์ œ

string์ด ์ฃผ์–ด์ง€๋Š”๋ฐ, ์•ŒํŒŒ๋ฒณ์„ ๋ชจ๋‘ ์†Œ๋ฌธ์ž๋กœ ๋ณ€๊ฒฝํ•˜๊ณ  ๋‚˜๋จธ์ง€ ๋ฌธ์ž๋Š” ์ œ์™ธํ•˜์˜€์„๋•Œ ์ด ๋ฌธ์ž์—ด์ด ํšŒ๋ฌธ์ธ์ง€๋ฅผ ํŒ๋‹จํ•œ๋‹ค.

์˜ˆ์‹œ) Example 1:

Input: s = โ€œA man, a plan, a canal: Panamaโ€ Output: true Explanation: โ€œamanaplanacanalpanamaโ€ is a palindrome. Example 2:

Input: s = โ€œrace a carโ€ Output: false Explanation: โ€œraceacarโ€ is not a palindrome. Example 3:

Input: s = โ€œ โ€œ Output: true Explanation: s is an empty string โ€œโ€ after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.

ํ’€์ด

import re
class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.lower()
        s = re.sub(r'[^a-z]',"",s)
        if s == s[::-1]:
            return True
        else: return False

์•Œ๊ฒŒ๋œ ์ 

  • ๋ฌธ์ œ์—์„œ alphanumeric์ด๋ผ๊ณ  ํ•œ๋‹ค๋ฉด ์•ŒํŒŒ๋ฒณ ๋ฟ ์•„๋‹ˆ๋ผ ์ˆซ์ž๋„ ๋‚จ๊ฒจ์•ผ ํ•œ๋‹ค. ๋‚˜๋Š” ๊ทธ๋ƒฅ ์•ŒํŒŒ๋ฒณ ๋นผ๋ฉด ๋‹ค ๋‚จ๊ธฐ๋Š”์ค„ ์•Œ์•„์„œ ์•„๋‹Œ๊ฑด ์‚ญ์ œํ•˜๋Š” ์ •๊ทœ ํ‘œํ˜„์‹์„ ์ผ๋Š”๋ฐ, ์ด๋Ÿฐ ๊ฒฝ์šฐ์—๋Š” isalpha()์ˆ˜์‹์„ ์“ธ ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•œ๋‹ค. ๊ทธ์น˜๋งŒ ์˜์–ด๊ฐ€ ๋ชจ๊ตญ์–ด๊ฐ€ ์•„๋‹Œ ์‚ฌ๋žŒ์ด ์•Œ๊ธฐ๋Š” ์–ด๋ ต๋‹ค.
  • ๋ฌธ์ž์—ด ์Šฌ๋ผ์ด์‹ฑ์—์„œ ๊ฑฐ๊พธ๋กœ ๋’ค์ง‘์–ด๋ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์„ ํƒ์ง€๊ฐ€ ์žˆ๋‹ค.
    text = "hello"
    reversed_text = ''.join(reversed(text))
    

    reversed๋Š” ๋ฆฌ์ŠคํŠธ๋ฅผ ๋’ค์ง‘์–ด์ฃผ๋Š”๋ฐ, reversed๋œ ๊ฑธ ๊ทธ๋Œ€๋กœ printํ•˜๋ฉด ๊ฐ์ฒด ์ž์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋ฆฌ์ŠคํŠธ๋ฅผ ์ฆ‰์‹œ ๋’ค์ง‘์–ด์„œ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š๊ณ  ๋ฐ˜๋ณต์ž(iterator)๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋ฐ˜๋ณต์ž๋Š” ์›๋ณธ ๋ฐ์ดํ„ฐ๋ฅผ ํ•œ๋ฒˆ์— ํ•˜๋‚˜์”ฉ ์ฝ์„ ์ˆ˜ ์žˆ์ง€๋งŒ, ์ง์ ‘ ์ถœ๋ ฅํ•˜๋ฉด ๊ฐ์ฒด์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ์ด๋ฅผ ๋‹ค์‹œ ๋ฆฌ์ŠคํŠธ๋‚˜ ๋ฌธ์ž์—ด๋กœ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ณผ์ •์ด ํ•„์š”ํ•˜๋‹ค!

Leave a comment