Leetcode [Easy] 125 - Valid Palindrome
LeetCode 125
Valid Anagram
문제
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
Constraints:
s consists only of printable ASCII characters.
나의 코드
function isPalindrome(s: string): boolean {
const text: string[] = s.split("").reduce((acc: string[], c: string) => {
if (/[A-Za-z0-9]/.test(c)) {
acc.push(c.toLowerCase());
}
return acc;
}, []);
if (!text.length) return true;
let left: number = 0;
let right: number = text.length - 1;
while (left < right) {
if (text[left] !== text[right]) return false;
left++;
right--;
}
return true;
}
참고 코드
// 1 (실패 코드이지만 참고)
var isPalindrome = function (s) {
var strippedString = s.replace(/\W/g, "");
var reversedString = strippedString.split("").reverse().join("");
return strippedString.toLowerCase() == reversedString.toLowerCase();
};
// 2
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (input) {
var start = 0;
var end = input.length - 1;
while (start < end) {
var s = input.charCodeAt(start);
var e = input.charCodeAt(end);
if (!isLetter(s)) {
start++;
continue;
}
if (!isLetter(e)) {
end--;
continue;
}
if (toLowerCase(s) !== toLowerCase(e)) {
return false;
}
start++;
end--;
}
return true;
};
var isLetter = function (code) {
if (
(code >= 48 && code <= 57) || // numbers
(code >= 65 && code <= 90) || // uppercase
(code >= 97 && code <= 122)
) {
// lowercase
return true;
} else {
return false;
}
};
var toLowerCase = function (code) {
if (code >= 65 && code <= 90) {
return code + 32;
} else {
return code;
}
};
배운점
-
charCode
를 사용해 소문자 변환, 문자 검증하는 것 신기함 -
정규식
\w
: any type of word 검색 (“[A-Za-z0-9_]” 와 동일)\W
: not\w
\w*
: any type of word 중 길이 0 또는 0 이상인 모든 것 검색
Subscribe via RSS