Encountered a seemingly simple problem while coding, but the expected returns started deviating as I progressed.
Your assistance would be greatly appreciated. If you do provide help, please elaborate on your approach and where I hit a roadblock.
The Challenge:
We are presented with a string and tasked with determining if it can be broken down into words from an array of words. For instance:
const str = "applecomputer"; const dictArr = ["apple", "computer"]; stringBreakdown(str, dictArr); // true
Considering no duplicates in the dictionary array, can you write a method to return true if the string can be segmented into words from the array, or false otherwise?
The Two Test Cases:
Expect stringBreakdown('crazyrichasians', [ 'crazy', 'rich', 'asians' ]) // to return true
Expect stringBreakdown('lockcombination', [ 'lock', 'combo' ]) // to return false
My Code and Strategy:
- Generate a hash map of all characters in the string
- Create a helper function to remove characters from each word in the array
- Reduce the count for each seen character in the hash map while removing characters from the word
- If all letters are accounted for, remove the word from the array
- Finally, return true if the array length is less than zero, indicating successful segmentation, or false if more words remain untouched
const stringBreakdown = (str, dictArr)=> {
let hashDictionary = {};
let shouldRemoveWord
for(let x = 0; x <= str.length-1;x++){
!hashDictionary[str[x]] ? hashDictionary[str[x]] =1 : hashDictionary[str[x]]+=1
}
for(let y = 0; y < dictArr.length;y++ ){
shouldRemoveWord = removeLetters(hashDictionary,dictArr[y])
if(shouldRemoveWord === true){
dictArr.splice(y,1)
}
}
console.log('dictArr',dictArr)
return dictArr.length > 0 ? true : false;
}
const removeLetters = (hash,word) =>{
let modifiedWord = word.split('')
for(let k = 0; k < modifiedWord.length;k++){
if(hash[word[k]]){
modifiedWord.splice(k,1)
hash[word[k]]-=1
}
}
return modifiedWord.join('').length < 0 ? true : false;
}