力扣1106.拼寫單詞-map

1、

2、

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        map<char,int> m;
        map<char,int> mp;
        vector<string> temp; 
        int res=0;
        int cnt=0;   
        if(words.size()>1000) return 0;    
        for(auto c : chars)
        {
            m[c]++;
            mp[c]++;
        }
        for(auto c : words)
        {
            cnt=0;
            mp=m;
            for(auto s : c)
            {
                if(m.find(s)==m.end()||m[s]==0)
                {
                    temp.emplace_back(c);
                    break;
                }
                if(m.find(s)!=m.end()&&mp[s]!=0)
                {
                    cnt++;
                    mp[s]--;
                }
                if(cnt==c.length())
                {
                    res+=cnt;
                }
                //cnt=0;
            }
            
        }
        return res;
    }
};

一開始以爲是每個字母總共只能用一次。。。。。。。。

class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        map<char,int> m;
        vector<string> temp; 
        int cnt=0;   
        if(words.size()>1000) return 0;    
        for(auto c : chars)
        {
            m[c]++;
        }
        for(auto c : words)
        {
            cnt=0;
            for(auto s : c)
            {
                if(m.find(s)==m.end()||m[s]==0)
                {
                    temp.emplace_back(c);
                    break;
                }
                if(m.find(s)!=m.end()&&m[s]!=0)
                {
                    cnt++;
                }
                if(cnt==c.length())
                {
                    for(auto x : c)
                    {
                        m[x]--;
                    }
                }
                //cnt=0;
            }
            
        }
        int len=chars.length();
        int i=0;
        int j=0;
        for(auto c : words)
        {
            for(auto s : c)
            {
                i++;
            }
        }
        for(auto c : temp)
        {
            for(auto s : c)
            {
                j++;
            }
        }
        return i-j;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章