// Source : https://leetcode-cn.com/problems/find-common-characters/
// Date : 2022-1-25
class Solution { public: vectorcommonChars(vector & words) { vector minfreq(26, INT_MAX); vector freq(26); for (const string& word: words) { //因为涉及到自增的问题,因此这里必须给数组填充0 fill(freq.begin(), freq.end(), 0); //将每个单词的出现次数放入数组中,下标从0--25 for (char ch: word) ++freq[ch - 'a']; for (int i = 0; i < 26; ++i) //从index入手,将最小的赋值 minfreq[i] = min(minfreq[i], freq[i]); } vector ans; for (int i = 0; i < 26; ++i) { for (int j = 0; j < minfreq[i]; ++j) { //如果一个元素出现多次,则需要把这个元素都添加进结果数组,注意:从Index转换到字符的方式 ans.emplace_back(1, i + 'a'); } } return ans; } };
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)