美文网首页
2020-03-17 刷题1(字符串)

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

作者: nowherespyfly | 来源:发表于2020-03-17 11:33 被阅读0次

    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;
        }
    };
    

    相关文章

      网友评论

          本文标题:2020-03-17 刷题1(字符串)

          本文链接:https://www.haomeiwen.com/subject/zfozehtx.html