From 4bc2b28b7eaadb9d04e2ba2e65c596c7b5be2355 Mon Sep 17 00:00:00 2001 From: Lokesh Patil <43759648+IamLokesh@users.noreply.github.com> Date: Wed, 17 Feb 2021 01:48:00 +0530 Subject: [PATCH] #559 Improve Palindrome check * #559 * #559 * #559 * #559 Co-authored-by: LOkesh --- String/CheckPalindrome.js | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/String/CheckPalindrome.js b/String/CheckPalindrome.js index 0ed1c6437..cca2620a6 100644 --- a/String/CheckPalindrome.js +++ b/String/CheckPalindrome.js @@ -5,20 +5,13 @@ const checkPalindrome = (str) => { if (typeof str !== 'string') { return 'Not a string' } - // Store the length of the input string in a variable - const length = str.length - if (length === 0) { + if (str.length === 0) { return 'Empty string' } - // Iterate through the length of the string - // Compare the first character to the last, the second character to the second last, and so on - for (let i = 0; i < length / 2; i++) { - // at the first instance of a mismatch - if (str[i] !== str[length - 1 - i]) { - return 'Not a Palindrome' - } - } - return 'Palindrome' + // Reverse only works with array, thus conevert the string to array, reverse it and convert back to string + // return as palindrome if the reversed string is equal to the input string + const reversed = [...str].reverse().join('') + return str === reversed ? 'Palindrome' : 'Not a Palindrome' } export { checkPalindrome }