JSFiddle - React, Tailwind, and code Playground
by kkdaily
HTML
<h3>
(CTCI 1.2) given two strings, write a method to decide if one is a permutation of the other
</h3>
<div id="message"></div>
CSS
#message {
padding: 10px;
}
.success {
background-color: lightgreen;
}
.failure {
background-color: pink;
}
JavaScript
// ex: 'cat', 'tac'
// 1. check that the lengths of the 2 strings are equal. If not, then return false for isPermutation
// 2. split out str1 into an array of chars (['c', 'a', 't'])
// 3. loop over str1 and check if the char exists in str2 (if (str2.indexOf(str1[i])) !== -1)
// 4. if the char exists in str2, then remove the char from str2 (str2 = str2.replace(str1[i], ''))
// 5. else, break the for loop and return false for isPermutation
isPermutation = (str1, str2) => {
if (str1.length !== str2.length) {
return false
}
let isPermutation = true
const str1Chars = str1.split('')
for (let i = 0; i < str2.length; i++) {
if (str2.indexOf(str1[i]) !== -1) {
str2 = str2.replace(str1[i], '')
} else {
isPermutation = false
break
}
}
return isPermutation
}
// TEST CASES
const messageEl = document.getElementById('message')
if (
isPermutation('cat', 'tac') === true &&
isPermutation('a', 'a') === true &&
isPermutation('abba', 'aba') === false &&
isPermutation('a', 'b') === false &&
isPermutation('cat', 'cat') === true
) {
messageEl.innerText = 'All tests passed!'
messageEl.classList.add('success')
} else {
messageEl.innerText = 'One or more tests failed'
messageEl.classList.add('failure')
}