Skip to content

Commit 8150356

Browse files
Fixes: #155 - Check if a string rearranged can be a palindrome (#407)
* Check if a string rearranged can be a palindrome * Fixes: #155 - palindromeRearranging * Update CheckRearrangePalindrome.js Co-authored-by: vinayak <itssvinayak@gmail.com>
1 parent 1671ea6 commit 8150356

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

String/CheckRearrangePalindrome.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* What is a palindrome? https://en.wikipedia.org/wiki/Palindrome
3+
* Receives a string and returns whether it can be rearranged to become a palindrome or not
4+
* The string can only be a palindrome if the count of ALL characters is even or if the ONLY ONE character count is odd
5+
* Input is a string
6+
*
7+
**/
8+
9+
const palindromeRearranging = (str) => {
10+
// check that input is a string
11+
if (typeof str !== 'string') {
12+
return 'Not a string'
13+
}
14+
// Check if is a empty string
15+
if (str.length === 0) {
16+
return 'Empty string'
17+
}
18+
19+
// First obtain the character count for each character in the string and store it in an object.
20+
// Filter the object's values to only the odd character counts.
21+
const charCounts = [...str].reduce((counts, char) => {
22+
counts[char] = counts[char] ? counts[char] + 1 : 1
23+
return counts
24+
}, {})
25+
// If the length of the resulting array is 0 or 1, the string can be a palindrome.
26+
return Object.values(charCounts).filter(count => count % 2 !== 0).length <= 1
27+
}
28+
29+
// testing
30+
console.log(palindromeRearranging('aaeccrr')) // true
31+
console.log(palindromeRearranging('leve')) // false

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy