1160. Find Words That Can Be Formed by Characters 拼寫單詞 (統計字母數量的常用方法)
- 2020 年 3 月 17 日
- 筆記
題目:
思路:
思路很簡單,只要分別統計chars中和每個單詞中字母出現的個數,chars中的字母大於等於每個單詞中的字母的個數,這個單詞便是good
可以利用C++中的map實現,現在記錄一種更靈活更常用的方式,凡是要統計字母個數,都可以這樣處理:
創建一個數組vec[26],每個位置分別存儲的是26個字母中對應字母的個數,以 char – ‘a‘ 的方式得到字母的索引
程式碼:
class Solution { public: vector<int> getV(string strings){ vector<int> res(26); for(char str: strings){ res[str - 'a']++; } return res; } int countCharacters(vector<string>& words, string chars) { vector<int> vec = getV(chars); vector<int> cur; int res=0; for(string word: words){ cur = getV(word); int i; for(i=0; i<26; i++){ if(cur[i] > vec[i]) break; } if(i == 26) res+=word.size(); } return res; } };