팰린드롬 (Palindrome) 설명:
팰린드롬은 순서를 거꾸로 읽었을 때도 원래의 문자열이나 수열과 동일한 경우를 의미합니다. 즉, 앞에서 읽을 때와 뒤에서 읽을 때의 모양이 같으면 팰린드롬이라고 합니다.
예시:
팰린드롬 검사 방법:
자바스크립트로의 구현 예:
function isPalindrome(s) {
// 문자열에서 알파벳과 숫자만을 추출
const cleanedString = s.replace(/[^A-Za-z0-9]/g, '').toLowerCase();
let left = 0;
let right = cleanedString.length - 1;
while (left < right) {
if (cleanedString[left] !== cleanedString[right]) {
return false;
}
left++;
right--;
}
return true;
}
console.log(isPalindrome("A man, a plan, a canal, Panama!")); // 출력: true
console.log(isPalindrome("racecar")); // 출력: true
console.log(isPalindrome("hello")); // 출력: false
해설:
isPalindrome 함수는 먼저 주어진 문자열에서 알파벳과 숫자만을 추출하여 소문자로 변환한 후, 팰린드롬인지 검사합니다.팰린드롬은 많은 알고리즘 문제에서 주제로 사용되며, 위의 방법은 팰린드롬을 확인하는 가장 기본적이고 간단한 방법 중 하나입니다.