CS/PS

[PS] Leet | 125. 팰린드롬 찾기

Rayi 2025. 6. 20. 15:07

문제

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.

조건

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

일반적인 팰린드롬 문제이지만, 입력값에 숫자나 문자가 아닌 다른 값이 섞여 있는게 차이입니다.

 

정규식을 통해 간단하게 제거할 수 있습니다.

 

이후는 팰린드롬 문제과 동일하게 해결합니다.

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    const str = s.toLowerCase().replace(/[^a-z0-9]/g, '');
    return str === str.split('').reverse().join('')
};

 

728x90