JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<p>
Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
Input: Tact Coa
Output: True (permutations: "taco cat", "atco cta", etc.)
</p>
JavaScript
// abab -> abba, baab
// odd length str must have an even number of each char AND must have 1 odd number of char
// even length str must have an even number of each char
// single length str automatically returns true
/*
- if length of str is 1, then return true
- split string into individual chars
- loop through chars
- if the current char is not an empty space
- if the char already exists in hash table, then increment that key's value by 1
- else add the char to the hash table with value 1
- increment lengthOfStr by 1
- if lengthOfStr is even, then set isEven to true
- else set isEven to false
- loop through hash table keys
- increment oddNumberOfChars by 1 for every odd valued key
- if isEven is true
- return false if oddNumberOfChars is > 0
- if isEven if false
- return false if oddNumberOfChars !== 1
*/
const isPermutationOfPalindrome = (str) => {
if (str.length <= 1) {
return false;
}
const chars = str.split(''); // ['a', 'b', 'a']
const charTracker = {}; // { 'a': 2, 'b': 1}
let oddNumOfChars = 0;
let numOfChars = 0;
for (let i = 0; i < chars.length; i++) {
if (chars[i] !== ' ') {
if (charTracker[chars[i]]) {
charTracker[chars[i]] += 1;
} else {
charTracker[chars[i]] = 1;
}
numOfChars++;
}
}
for (let char in charTracker) {
if (charTracker[char] % 2 !== 0) {
oddNumOfChars++;
}
}
if (numOfChars % 2 === 0) {
if (oddNumOfChars === 0) {
return true;
}
} else {
if (oddNumOfChars === 1) {
return true;
}
}
return false;
}
const a = isPermutationOfPalindrome('aaabccb');
alert(a);