Introduction
A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward, ignoring spaces, punctuation, and capitalization. Checking whether a string is a palindrome is a common problem in programming and can be approached in various ways. This guide will walk you through different methods to determine if a given string is a palindrome using JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts a string input.
- Determines whether the string is a palindrome.
- Returns a boolean value (
true
orfalse
) indicating the result.
Example:
Input:
"radar"
Output:
true
Input:
"hello"
Output:
false
Solution Steps
- Read the Input String: Accept the string input from the user or define it directly in the program.
- Normalize the String: Convert the string to a consistent case (e.g., all lowercase) and remove non-alphanumeric characters to ensure accurate comparison.
- Check for Palindrome: Implement different methods—using built-in functions, iterative comparison, and recursive checking—to determine if the string is a palindrome.
- Display the Result: Output the boolean result (
true
orfalse
) for each method.
Method 1: Using Built-in Functions
// JavaScript Program to Check if a String is Palindrome Using Built-in Functions
// Author: https://www.javaguides.net/
function isPalindromeBuiltIn(str) {
// Step 1: Normalize the string
const normalizedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Step 2: Reverse the string
const reversedStr = normalizedStr.split('').reverse().join('');
// Step 3: Compare the original and reversed strings
return normalizedStr === reversedStr;
}
// Example input
let inputString = "Radar";
let result = isPalindromeBuiltIn(inputString);
console.log(`Is "${inputString}" a palindrome? ${result}`);
Output:
Is "Radar" a palindrome? true
Explanation:
- Normalization: Converts the string to lowercase and removes any non-alphanumeric characters to ensure a fair comparison.
- Reversing: Splits the string into an array of characters, reverses the array, and joins it back into a string.
- Comparison: Checks if the normalized string is equal to its reversed version.
Method 2: Iterative Approach
// JavaScript Program to Check if a String is Palindrome Using Iteration
// Author: https://www.javaguides.net/
function isPalindromeIterative(str) {
// Step 1: Normalize the string
const normalizedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Step 2: Initialize pointers
let left = 0;
let right = normalizedStr.length - 1;
// Step 3: Compare characters from both ends
while (left < right) {
if (normalizedStr[left] !== normalizedStr[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Example input
result = isPalindromeIterative(inputString);
console.log(`Is "${inputString}" a palindrome? ${result}`);
Output:
Is "Radar" a palindrome? true
Explanation:
- Normalization: Similar to the first method, it ensures the string is in a consistent format.
- Pointers: Uses two pointers, one starting at the beginning (
left
) and the other at the end (right
) of the string. - Comparison: Iteratively compares characters from both ends moving towards the center. If any pair of characters doesn't match, it returns
false
. If all pairs match, it returnstrue
.
Method 3: Recursive Approach
// JavaScript Program to Check if a String is Palindrome Using Recursion
// Author: https://www.javaguides.net/
function isPalindromeRecursive(str) {
// Step 1: Normalize the string
const normalizedStr = str.toLowerCase().replace(/[^a-z0-9]/g, '');
// Step 2: Define the recursive function
function checkPalindrome(left, right) {
if (left >= right) {
return true;
}
if (normalizedStr[left] !== normalizedStr[right]) {
return false;
}
return checkPalindrome(left + 1, right - 1);
}
// Step 3: Initiate the recursive check
return checkPalindrome(0, normalizedStr.length - 1);
}
// Example input
result = isPalindromeRecursive(inputString);
console.log(`Is "${inputString}" a palindrome? ${result}`);
Output:
Is "Radar" a palindrome? true
Explanation:
- Normalization: Ensures the string is in a consistent format for comparison.
- Recursive Function: Defines a helper function
checkPalindrome
that takes two indices (left
andright
). It compares the characters at these indices and recursively moves towards the center. - Base Cases: If
left
is greater than or equal toright
, it means all characters have been successfully compared. If any pair doesn't match, it returnsfalse
.
Conclusion
This JavaScript program demonstrates three methods to check whether a string is a palindrome:
- Built-in Functions: Utilizes JavaScript's string and array methods to reverse the string and compare it with the original.
- Iterative Approach: Uses a two-pointer technique to compare characters from both ends of the string moving towards the center.
- Recursive Approach: Implements a recursive function to compare characters at corresponding positions from the start and end.
Each method has its advantages:
- Built-in Functions are concise and easy to implement but may not be the most efficient for very long strings.
- Iterative Approach is efficient and avoids the overhead of recursive calls.
- Recursive Approach offers a clear and elegant solution but can lead to stack overflow issues with very long strings due to deep recursion.
Choose the method that best fits your specific use case and performance requirements.
Comments
Post a Comment
Leave Comment