Algorithm
[LeetCode] Valid Palindrome
죠죠_
2023. 9. 14. 17:12
문제
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를 반환하고, 그렇지 않으면 fasle를 반환합니다.
*주의사항 : s = " " 인 경우, 영숫자가 아닌 문자를 모두 지우면 ""가 된다. 빈 문자열 역시 앞뒤가 동일하게 읽히기 때문에 이는 회문으로 간주한다.
풀이
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
const reg = /[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/ ]/gim;
const text = s.toLowerCase().replaceAll(reg,'');
const array = Array.from(text);
let right = array.length - 1;
let result = false;
if (text === "") return true;
for (let left = 0; left < array.length / 2; left++) {
if (array[left] === array[right]) {
result = true;
right--;
} else {
return false;
}
}
return result;
};
1. 문자열의 모든 글자를 소문자로 변경
2. 정규표현식을 활용해 영숫자가 아닌 특수문자를 지워준다.
3. 순수하게 문자열만 남은 text를 배열로 변경
4. 앞뒤가 같은지 여부를 확인하기 위해 2개의 포인터를 두어 체크
5. 포인터를 이동하며 left와 right가 같은지 확인하고 다른경우를 발견하면 바로 false를 반환한다.
Runtime: 64 ms
Memory Usage: 45.2 MB