Day - 10
Hello, dears. It is me again! I am coming up with a good solution for the LeetCode problem. You know, consistency is key to success. So I am trying my best to complete my challenge on time. I appreciate your attention.
If you like this post, share it with your friends. Maybe, because of you someone starts a challenge on himself or herself.
Ok, we will continue! You can see my solution below!
领英推荐
var commonChars = function (words)
let res = [];
let hash = hashWord(words[0]);
for (let i = 1; i < words.length; i++) {
let word = words[i];
let tempHash = hashWord(word);
merge(hash, tempHash);
}
for (let [letter, count] of Object.entries(hash)) {
while (0 < count--) {
res.push(letter);
}
}
return res;
};
function hashWord(word) {
let hash = {};
for (let i = 0; i < word.length; i++) {
let letter = word[i];
if (hash[letter]) {
hash[letter]++;
} else {
hash[letter] = 1;
}
}
return hash;
};
function merge(hash1, hash2) {
for (let letter of Object.keys(hash1)) {
if (!hash2[letter]) {
delete hash1[letter];
} else {
hash1[letter] = Math.min(hash1[letter], hash2[letter]);
}
}
};
Huuhh. This solution made me think more than others.
Thanks for your valuable time! I will come up with other solutions in the next few days!
See you!