MakerHyeon

[LeetCode] 125. Valid Palindrome (python,C++) 본문

Algorithm/LeetCode

[LeetCode] 125. Valid Palindrome (python,C++)

유쾌한고등어 2023. 3. 8. 15:39

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

 

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

  • ord(문자)
    하나의 문자를 인자로 받고 해당 문자에 해당하는 유니코드 정수를 반환
    ex_ ord('a')를 넣으면 정수 97을 반환
  • chr(정수)
    하나의 정수를 인자로 받고 해당 정수에 해당하는 유니코드 문자를 반환
    인자(정수)의 유효 범위는 0 ~ 1,114,111 (16진수 0x10 FFFF)까지 입니다.
    ex_ chr(97)을 하면 문자 'a'를 반환

SOLUTION CODE

# PYTHON

 

1) 메모리복잡도 O(n)

class Solution:
    def isPalindrome(self, s: str) -> bool:
        newStr=""
        for c in s:
            if c.isalnum():
                newStr+=c.lower()
        return newStr==newStr[::-1]

1) 메모리복잡도 O(1)

class Solution:
    def isPalindrome(self, s: str) -> bool:
        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'))

 

# C++

class Solution {
public:
    bool isPalindrome(string s) {
        int l=0;
        int r=s.size()-1;

        while(l<r){
            while(l<r && !isalnum(s[l])) l++;
            while(r>l && !isalnum(s[r])) r--;

            if(tolower(s[l])!=tolower(s[r])) return false;
            l++;
            r--;
        }
        return true;
    }
};

 

 

 

Comments