JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<p>
Given 2 strings write a method to decide if one is a permutation of the other
</p>
JavaScript
var str1 = 'dog';
var str2 = 'god';
// var str1 = 'dog';
// var str2 = 'gog';
/*
presort both arrays alphabetically
while i < str1.length
compare str1[i] with str2[i]
if they are equal
continue
else
break and return false
return true
checkIfCharsAreEqual method
*/
const checkIfPermutation = (str1, str2) => {
if (str1.length !== str2.length) {
return false;
}
const chars1 = str1.split(''); // ['d', 'o', 'g']
const chars2 = str2.split(''); // ['g', 'o', 'g']
chars1.sort(); // ['d', 'g', 'o']
chars2.sort(); // ['g', 'g', 'o']
return charsArePermutation(chars1, chars2);
}
const charsArePermutation = (chars1, chars2) => {
let i = 0;
let isPermutation = true;
while (i < chars1.length) {
if (chars1[i] !== chars2[i]) { // 'd' !== 'g'
isPermutation = false;
}
i++;
}
return isPermutation;
}
const a = checkIfPermutation(str1, str2);
alert(a);