수쿵의 IT월드

DaleStudy | Leetcode Study 3주차 - Valid Palindrome 본문

알고리즘

DaleStudy | Leetcode Study 3주차 - Valid Palindrome

수쿵IT 2025. 8. 9. 14:15

Leetcode Study

문제

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.

 

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.

 

Constraints:

  • 1 <= s.length <= 10^5
  • s consists only of printable ASCII characters.

 

풀이

function isPalindrome(s: string): boolean {
    const cleanString = s.toLowerCase().replace(/\s+/g, '').replace(/[^a-z0-9]/g, '');

    let left = 0;
    let right = cleanString.length - 1;

    while (left < right) {
        if (cleanString[left] !== cleanString[right]) {
            return false;
        }

        left++;
        right--;
    }

    return true;
};

 

이 문제는 비교적 단순한데, replace를 이용해서 특수문자와 공백을 제거한 뒤에 왼쪽과 오른쪽을 하나씩 옮겨가며 체크하면 된다. 2개의 문자가 다르면 false를 리턴하고 루프문이 끝나면 모든 문자가 동일하다는 뜻이므로 true를 리턴해주면 된다. 

 

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