Blind 75 | Valid Palindrome (Two Pointers 1 / 3)
https://leetcode.com/problems/valid-palindrome/
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
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.
모든 대문자를 소문자로 바꾼 후 알파벳과 숫자를 제외한 모든 문자를 제거하고, 앞과 뒤에서부터 똑같이 읽히는 문장은 회문이다. 문자열 s가 주어졌을 때, 회문이면 true를 아니면 false를 리턴하라.
개요
투포인터의 기본 문제로 처음부터 비교하기 쉽게 문자열을 정제하면 편하다.
풀이 방법
Regex로 문자열을 정제한 후 투포인터 기법을 사용해서 처음과 끝을 비교한다.
만약 둘이 다르다면 false를 리턴하고 같다면 문자열의 중앙부까지 left를 증가시키고 right을 감소시키며 하나씩 비교한다.
풀이
많이 나오는 regex 패턴중에 하나인데
/[a-z0-9]+/g는 모든 소문자 알파벳과 숫자를 포함하고
/[^a-z0-9]+/g는 알파벳과 숫자를 제외한 모든 문자열을 포함한다.
따로 charCode로 알파벳을 구분하거나 Number로 바꾼 뒤에 Number.isNaN으로 확인하는 방법도 있지만
이처럼 자주 나오는 regex 패턴은 익숙해지면 시간을 아낄 수 있다.