LeetCode Valid Palindrome (JavaScript)

2026. 1. 26. 12:54·코딩테스트/LeetCode

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

문제 설명

더보기

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 <= 2 * 105
  • s consists only of printable ASCII characters.

문제 풀이

문자열 비교를 쉽게 하기 위해 전부 대문자로 변경

이후 left, right 2개의 포인터를 두어 각각 왼쪽, 오른쪽에서 같은 값을 가지는지 검사

-> 중간에 실패할 경우 palindrome 문자가 아님 return false

while 문이 끝나면 palindrome 문자로 return true

/**
 * @param {string} s
 * @return {boolean}
 */
var isPalindrome = function(s) {
    s = s.toUpperCase();
    let [left, right] = [0, s.length - 1];

    while (left < right) {
        while (left < right && !(s[left] >= '0' && s[left] <= '9') && !(s[left] >= 'A' && s[left] <= 'Z')) {
            left++;
        }

        while (left < right && !(s[right] >= '0' && s[right] <= '9') && !(s[right] >= 'A' && s[right] <= 'Z')) {
            right--;
        }

        if (s[left] !== s[right]) {
            return false;
        }
        
        left++;
        right--;
    }

    return true;
};

결론

O(n)의 시간복잡도로 해결하기 위해 left, right 의 포인터를 적절하게 이용하면 됨.

while 문 내부에 0~9, A~Z를 탐색하기 위한 while 문을 쉽게 적용하려면 정규 표현식으로 숫자 또는 문자만 포함되게 설정하면 더 짧게 코드를 작성할 수 있음

// 0~9, A~Z만 포함하는 문자열
s.toUpperCase().replace(/[^0-9A-Z]/g, '');

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Number of Islands (JavaScript), DFS  (1) 2026.01.27
LeetCode Best Time to Buy and Sell Stock (JavaScript)  (0) 2025.12.28
LeetCode Decode Ways (JavaScript), (DFS, Memoization)  (0) 2025.12.22
LeetCode Triangle (JavaScript)  (0) 2025.12.19
LeetCode Subsets ll (JavaScript), backtracking  (0) 2025.12.18
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Number of Islands (JavaScript), DFS
  • LeetCode Best Time to Buy and Sell Stock (JavaScript)
  • LeetCode Decode Ways (JavaScript), (DFS, Memoization)
  • LeetCode Triangle (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (218)
      • 프론트엔드 (65)
        • JavaScript (52)
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (131)
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (42)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Valid Palindrome (JavaScript)
상단으로

티스토리툴바