思路
维护一个容量为26的数组,遍历字符chars对每个字母计数
之后使用这张计数表,去对照words内每一个单词,遇到对应字母就-1
若遇到0就跳出,并不计算长度。若整个单词遍历完,就记录改单词长度
实现
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
int res = 0;
int set[26] = {0};
for(auto c: chars) set[c-'a']++;
for(auto word: words){
bool flag = true;
int temp[26];
copy(set, set+26, temp);
for(auto c: word){
if(temp[c-'a']==0){
flag = false;
break;
}else{
temp[c-'a']--;
}
}
if(flag) res += word.length();
}
return res;
}
};
优化
在题解当中看到最快题解,在循环中加入了std::ios::sync_with_stdio(false);
加入IO优化后,的确速度提升
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。