Day1 of the #100DaysOfAlgorithms Palindrome Checker
2 min readApr 15, 2023
Write a function that takes a string as input and checks if it is a palindrome.
A palindrome is a word, phrase, number, or another sequence of characters that reads the same backward or forward (ignoring spaces, punctuation, and capitalization).
Solution
Characteristics of a palindrome
- The first letter is equal to the last letter
- The second letter is equal to the last second letter
- Compare the first nth letter to the last nth letter
- A single character is not a palindrome
- An empty string is not a palindrome
- A palindrome does not contain special characters
- A palindrome can contain a number
Code
function compareChar(firstChar: string, lastChar: string): boolean {
return firstChar === lastChar ? true : false
}
function isPolindrome(input: string): any {
let isPolindrome: boolean = true
if (input === '') {
isPolindrome = false
} else {
let newInput: any = input.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()
let textArr: any[] = newInput.split('')
let arrySize: number = textArr.length
if(arrySize === 1){
isPolindrome = false
}else{
for (let i = 0; i < textArr.length; i++) {
console.log(
'From first: ' + textArr[i],
'From Last: ' + textArr[arrySize - 1 - i]
)
if (
compareChar(textArr[i], textArr[arrySize - 1 - i]) === false
) {
isPolindrome = false
break
}
}
}
}
if(isPolindrome){
console.log("is polindrome")
}else{
console.log("Is not polindrome")
}
}
isPolindrome('')