写一个方法判断字符串是否为回文字符串
/**
* Checks if a given string is a palindrome.
*
* @param {string} str The string to check.
* @param {boolean} [caseSensitive=false] Whether the comparison should be case-sensitive.
* @returns {boolean} True if the string is a palindrome, false otherwise.
*/
function isPalindrome(str, caseSensitive = false) {
if (!str) {
return true; // Empty string is considered a palindrome
}
const processedStr = caseSensitive ? str : str.toLowerCase();
const reversedStr = processedStr.split('').reverse().join('');
return processedStr === reversedStr;
}
// Examples
console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("Racecar")); // false (case-sensitive by default)
console.log(isPalindrome("Racecar", true)); // false (case-sensitive)
console.log(isPalindrome("Racecar", false)); // true (case-insensitive)
console.log(isPalindrome("A man, a plan, a canal: Panama", false)); // true (ignores non-alphanumeric characters and case)
console.log(isPalindrome("")); // true (empty string)
console.log(isPalindrome(null)); // true (null/undefined treated as empty string)
/**
* More robust version handling non-alphanumeric characters.
*
* @param {string} str The string to check.
* @param {boolean} [caseSensitive=false] Whether the comparison should be case-sensitive.
* @returns {boolean} True if the string is a palindrome, false otherwise.
*/
function isPalindromeRobust(str, caseSensitive = false) {
if (!str) {
return true; // Empty string is considered a palindrome
}
const alphanumericStr = str.replace(/[^a-zA-Z0-9]/g, ''); // remove non-alphanumeric chars
const processedStr = caseSensitive ? alphanumericStr : alphanumericStr.toLowerCase();
let left = 0;
let right = processedStr.length - 1;
while (left < right) {
if (processedStr[left] !== processedStr[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Robust examples
console.log(isPalindromeRobust("A man, a plan, a canal: Panama")); // true
console.log(isPalindromeRobust("Race car!")); // true
console.log(isPalindromeRobust("Was it a car or a cat I saw?")); // true
console.log(isPalindromeRobust("hello")); // false
This code provides two functions:
-
isPalindrome(str, caseSensitive): A basic palindrome checker. It's concise but doesn't handle non-alphanumeric characters well. ThecaseSensitiveparameter lets you control whether case matters. -
isPalindromeRobust(str, caseSensitive): A more robust version that removes non-alphanumeric characters before checking. This is generally more useful for real-world scenarios. It also uses a two-pointer approach which is generally more efficient than reversing the entire string.
Both functions treat empty strings (and null/undefined) as palindromes. The examples demonstrate how to use them and the differences in their behavior. I've included comments to explain the code clearly. Choose the function that best suits your needs.
浙公网安备 33010602011771号