Skip to content

Commit 4bc2b28

Browse files
IamLokeshLOkesh
and
LOkesh
authored
#559 Improve Palindrome check
* #559 * #559 * #559 * #559 Co-authored-by: LOkesh <[email protected]>
1 parent 21b003e commit 4bc2b28

File tree

1 file changed

+5
-12
lines changed

1 file changed

+5
-12
lines changed

String/CheckPalindrome.js

+5-12
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,13 @@ const checkPalindrome = (str) => {
55
if (typeof str !== 'string') {
66
return 'Not a string'
77
}
8-
// Store the length of the input string in a variable
9-
const length = str.length
10-
if (length === 0) {
8+
if (str.length === 0) {
119
return 'Empty string'
1210
}
13-
// Iterate through the length of the string
14-
// Compare the first character to the last, the second character to the second last, and so on
15-
for (let i = 0; i < length / 2; i++) {
16-
// at the first instance of a mismatch
17-
if (str[i] !== str[length - 1 - i]) {
18-
return 'Not a Palindrome'
19-
}
20-
}
21-
return 'Palindrome'
11+
// Reverse only works with array, thus conevert the string to array, reverse it and convert back to string
12+
// return as palindrome if the reversed string is equal to the input string
13+
const reversed = [...str].reverse().join('')
14+
return str === reversed ? 'Palindrome' : 'Not a Palindrome'
2215
}
2316

2417
export { checkPalindrome }

0 commit comments

Comments
 (0)