【每日一题】1160. 拼写单词

原题链接

解题思路:
使用两个哈希表存储数据并对比,首先使用哈希表存储字母数据,然后二次循环对应比较,单词表中的字母数量字母表中的字母数量
如果前者不大于后者则说明能拼写成功,累加单词长度
Python解法

import collections
class Solution:
    def countCharacters(self, words, chars: str) -> int:
        chars_cnt=collections.Counter(chars)
        ans=0
        for word in words:
            word_cnt=collections.Counter(word)
            for i in word_cnt:
                if word_cnt[i]>chars_cnt[i]:
                    break
            else:
                ans+=len(word)
        return print(ans)

words=["cat","bt","hat","tree"]
chars="atach"

Solution().countCharacters(words,chars)

JavaScript解法:

/**
 * @param {string[]} words
 * @param {string} chars
 * @return {number}
 */
var countCharacters = function(words, chars) {
    let ans=0;
    let charMap=new Map();
    for (let char of chars){
        charMap.set(char,(charMap.has(char)?charMap.get(char)+1:1));
    }
    for (let word of words){

        let wordMap=new Map();

        for(let char of word){
            wordMap.set(char,(wordMap.has(char)?wordMap.get(char)+1:1))
        }

        let enough=true;

        for(let char of word){
        if(wordMap.get(char)>charMap.get(char)||charMap.get(char)===undefined){
            enough=false;
            break;
        }
        }
        if (enough){
            ans+=word.length
        }        
    }
    return ans
};
发布了34 篇原创文章 · 获赞 4 · 访问量 2177

猜你喜欢

转载自blog.csdn.net/qq_41629800/article/details/105407105