拼写单词
官方解法:
使用哈希表或者数组,记录字母表每个字母的个数,记录单词每个字母的个数,然后逐一比对。
如果单词中某个字母的个数大于字母表中该字母的个数,则不能拼写该单词。
遇到这类限定只有小写或大写字母的题,可以考虑用数组[26]来解决。
class Solution { public: int countCharacters(vector<string>& words, string chars) { int cnt = 0; string word; int charsArray[26] = {0}; int canSpell = true; count26Char(charsArray, chars, chars.size()); for(int i = 0; i < words.size(); i++){ canSpell = true; int wordArray[26] = {0}; count26Char(wordArray, words[i], words[i].size()); for(int j = 0; j < words[i].size(); j++){ if(wordArray[words[i][j]-'a'] > charsArray[words[i][j]-'a']){ canSpell = false; break; } } if(canSpell) cnt += words[i].size(); } return cnt; } void count26Char(int a[], string s, int len){ for(int i = 0; i < len; i++){ a[s[i]-'a']++; } } };
我的解法:
对单词和字母表的字母进行排序,然后逐一比对。
这里用到了快排。
class Solution { public: int countCharacters(vector<string>& words, string chars) { int cnt = 0; string word; quickSort(chars,0,chars.size()-1); for(int i = 0; i < words.size(); i++){ word = words[i]; quickSort(word,0,word.size()-1); int p = 0; int q = 0; while(q < chars.size() && p < word.size()){ if(word[p] == chars[q]){ p++; } q++; } if(p == word.size()) cnt += word.size(); } return cnt; } void quickSort(string &s, int l, int r){ if(l < r){ int i = l; int j = r; char x = s[i]; while(i < j){ while(i < j && s[j] >= x){ j--; } if(i < j) s[i++] = s[j]; while(i < j && s[i] < x){ i++; } if(i < j) s[j--] = s[i]; s[i] = x; } quickSort(s, l, i-1); quickSort(s, i+1, r); } } };