본문 바로가기
자료구조와 알고리즘

[DSA][Two Pointers] 01. Valid Palindrome

by varcode 2025. 6. 2.
반응형

LeetCode 125

 

01. 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 characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.

 

 

[질문하기]

- 숫자도 valid 한 문자인가요? → Alphanumeric에 해당하는 집합에 대한 정확한 정의

 

 

[아이디어]

- Two Pointer를 사용하여 양 끝에서 palidrome을 체크하자.

 

 

[풀이 1] Two Pointer

class Solution:
    def isAlphaNumeric(self, c: str) -> bool:
        if c.isalpha() or c.isdigit():
            return True
        return False

    def isPalindrome(self, s: str) -> bool:
        L, R = 0, len(s) - 1
        while L < R:
            while L < R and not self.isAlphaNumeric(s[L]):
                L += 1
            while L < R and not self.isAlphaNumeric(s[R]):
                R -= 1
            if s[L].lower() != s[R].lower():
                return False
            L += 1
            R -= 1
        return True

이 문제에서는 1) alphanumeric을 걸러내고 2) palindrome인지 확인하는 두 가지 과정이 필요하다.

처음부터 alphanumeric이 아닌 문자들을 걸러내고 lower 처리도 한 다음에 palindrome을 체크하는 방법도 있고, 위의 풀이처럼 지워가면서 비교하는 방법도 있다. 모든 while 문장에 L < R 조건이 붙어있는데, 이런 condition을 잘 넣어줘야 edge case에 안 걸리고 해답을 낼 수 있다.

 

⏱️ 시간복잡도

정수 배열을 한번 순회하기 때문에 O(n) 시간 복잡도를 갖는다.


🧠 공간복잡도

변수 공간만 필요하므로 O(1) 공간 복잡도를 갖는다.

반응형

댓글