2020-03-17 刷题1(字符串)

1160 拼写单词

题解的做法是用哈希表统计每个字母表中每个字母出现的次数,然后遍历每个单词,统计单词内每个字母出现次数,与字母表进行比较。不过我的做法是,用一个长度为26的数组来统计即可(因为只有小写字母),遍历到每个字母的时候减一。

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        short char_cnt[26] = {0}, tmp_cnt[26] = {0};
        for(int i = 0; i < chars.size(); i++){
            char_cnt[chars[i]-'a']++;
        }
        int total_len = 0;
        for(int i = 0; i < words.size(); i++){
            bool flag = true;
            memcpy(tmp_cnt, char_cnt, 26*sizeof(short));
            for(int j = 0; j < words[i].size(); j++){
                if(tmp_cnt[words[i][j]-'a'])
                    tmp_cnt[words[i][j]-'a']--;
                else{
                    flag = false;
                    break;
                }
            }
            if(flag)
                total_len += words[i].size();
        }
        return total_len;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容