Day1 of the #100DaysOfAlgorithms Palindrome Checker

Justine Peterson Mahinyila
2 min readApr 15, 2023

--

Photo by VD Photography on Unsplash

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

  1. The first letter is equal to the last letter
  2. The second letter is equal to the last second letter
  3. Compare the first nth letter to the last nth letter
  4. A single character is not a palindrome
  5. An empty string is not a palindrome
  6. A palindrome does not contain special characters
  7. 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('')

--

--

Justine Peterson Mahinyila
Justine Peterson Mahinyila

Written by Justine Peterson Mahinyila

My mission is to improve people’s lives and solve problems using technology in Africa

No responses yet