Skip to content

Instantly share code, notes, and snippets.

@lienista
Last active August 28, 2018 07:40
Show Gist options
  • Select an option

  • Save lienista/4b114ab61c550fc4688790fe9eface81 to your computer and use it in GitHub Desktop.

Select an option

Save lienista/4b114ab61c550fc4688790fe9eface81 to your computer and use it in GitHub Desktop.
Algorithms in Javascript: CTCI 1.4 Palindrome Permutation: Given a string, determine if it is a permutation of a palindrome.
const isPermutation = (s1, s2) => {
if(s1.length != s2.length) return false;
let count = new Map();
for (let i = 0; i < s1.length; ++i) {
count.set(s1[i], count.get(s1[i]) + 1 || 1);
}
for(let j = 0; j < s2.length; ++j) {
let num = count.get(s2[j]);
if (!num) return false;
if (num === 1) count.delete(s2[j]);
else count.set(s2[j], num - 1);
}
return count.size === 0;
}
var a = isPermutation("paypalishiring", "palpayhiringis"); // true
var b = isPermutation("paypalishiring", "hiringpalsipay"); // true
var c = isPermutation("paypalishiring", "palpayhirising"); // true
var d = isPermutation("paypalishiring", "palpayhiringgg"); // false
console.log(a + ', ' + b + ', ' + c + ', ' + d);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment