leetcode:1160. 拼写单词

题目来源

题目详情

在这里插入图片描述

在这里插入图片描述

题目解答

显然,对于一个单词 word,只要其中的每个字母的数量都不大于 chars 中对应的字母的数量,那么就可以用 chars 中的字母拼写出 word

class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
    vector<int> freq_bucket(26, 0);
    for(char ch : chars){
        freq_bucket[ch - 'a']++;
    }
    
    int sum = 0;
    for(const string& word : words){
        bool ok = true;
        vector<int> freq(freq_bucket);
        for(char ch : word){
            freq[ch - 'a']--;
            if(freq[ch - 'a'] < 0){
                ok = false;
                break;
            }
        }
        
        if(ok){
            sum = sum + word.length();
        }
    }

    return sum;
}
};
    // 所有字符串中都仅包含小写英文字母
    public static int countCharacters(String[] words, String chars) {
        int count = 0;
        int[] Hasi = new int[26];
        for (int i = 0; i < chars.length(); i++) {
            Hasi[chars.charAt(i) - 'a'] ++;
        }

        for (String word: words ) {
            int[] cc = Arrays.copyOf(Hasi, Hasi.length);
            boolean flag = true;
            for (char c: word.toCharArray()){
               if (cc[c-'a'] == 0){
                    flag = false;
                    break;
                }
                cc[c-'a']--;
            }

            if (flag){
                count = count + word.length();
            }
        }


        return count;
    }


    public static void main(String[] args) {
       System.out.println(countCharacters(new String[]{"cat","bt","hat","tree"}, "atach"));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值