[1002.查找常用字符]
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
int hashMap[100][26] = {0};
int count = 0;
int k =0;
string result[100];
for(int i =0; i < words.size(); i++){
for (int j = 0; j < words[i].size(); j++){
hashMap[i][words[i][j] - 'a']++;
}
}
for(int j = 0; j <= 26; j++){
for(int i=0; i < words.size()-1; i++){
if(hashMap[i][j] != hashMap[i+1][j])
break;
count = hashMap[i][j];
}
while(count--){
result[k] = j + 'a';
k++;
}
}
return result;
}
};
- 还没看卡哥思路 但字符串数组 不会用 先改改
- 就算改了 也有问题 数组是不能先访问列后访问行的 第二个For循环不正确
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
int hashMap[100][26] = {0};
int value[26] = {0};
vector<string> result;
int count = 0;
for(int i =0; i < words.size(); i++){
for (int j = 0; j < words[i].size(); j++){
hashMap[i][words[i][j] - 'a']++;
}
}
for(int j = 0; j < 26; j++){
for(int i=0; i < words.size() ; i++){
if(value[j] > hashMap[i][j])
value[j] = hashMap[i][j];
}
while(value[j]--){
string s(1, j + 'a'); // char -> string
result.push_back(s);
}
}
return result;
}
};
- 看到思路 “取每个字符频率最小值 为该字符最后输出的次数” 我就发现 我之前想的是“频率必须相等才能取 而且还要除以words里所含字符串总个数 才能确定 字符输出的次数”
class Solution {
public:
vector<string> commonChars(vector<string>& words) {
int hashMap[100][26] = {0};
int value[26] = {0};
vector<string> result;
int count = 0;
for(int i =0; i < words.size(); i++){
for (int j = 0; j < words[i].size(); j++){
hashMap[i][words[i][j] - 'a']++;
value[words[i][j] - 'a'] = hashMap[i][words[i][j] - 'a'];
}
}
for(int j = 0; j < 26; j++){
for(int i=0; i < words.size() ; i++){
if(value[j] > hashMap[i][j])
value[j] = hashMap[i][j];
}
while(value[j]--){
string s(1, j + 'a'); // char -> string
result.push_back(s);
}
}
return result;
}
};
- 本来想把我上面代码全部推翻的 但看了卡哥思路和代码之后 我发现 我们差不太多 区别是是在于: 比如words里有四个单词,他是先统计第一个单词各个字母出现的次数 一维数组hash[26]中》》》》》然后对剩下三个单词 进入次数为3的循环 {(当然 最开始不要忘记每进入一次该循环 都要讲hashOtherStr初始化 否则会影响下一次存储及判断)首先将各个字母出现的次数 放在一维数组hashOtherStr[26] 中, 接着对比这个数组和之前hash数组对应位置元素值大小 保证hash数组里存储的是较小值}》》》》》最后就是将hash[26]这个整形数组 每个下标值+‘a'转换成字母形式输出即可
- 我的思路是 还是比如words里有四个单词 我直接把这四个单词的每个字母出现的次数 一起填入一个hashMap[4] [26]的二维数组中 》》》》》》因为需要从这个二维数组中 的 每列中 选择出值最小的元素值 这样确定了次数 才能进行最后 转换成字母输出; 因此我设置了value[26] 这等价于卡哥的hash[26] 作为一个标准的作用 但是卡哥的hash初值是 第一个单词各字母次数 而我的value数组 从代码可以看出 它的元素值随着两层for循环一直在变 因此它存储的是最后一个单词中个字母出现的次数》》》》》》》最后的输出转化同卡哥
- 两个注意点:1. 输出转换 我知道需要和转换 这个思路 这个语句 我自己写不出来。往细了挖 就是我不知道如何 把char 变成string 再把string 变成string类型数组; 此外开头的 对字符串数组的操作 我也不熟悉 ; 具体这两类型基础语句见下:
//char变string变vector<string>
vector<string> result;
string s(1, j + 'a'); // char -> string
result.push_back(s);
//words = ["bella","label","roller"]取第二个字符串的第三个字母 方法类似普通二维数组即可
words[1][2];
- 第二个注意点 也是我提交前犯的一个错误 怎么运行结果是空值 原来我的value数组没赋初值 那么它的元素都是0 本来就比hashMap小 当然不用再进行别的操作了 结果就还是0 因此返回空值 看了卡哥的代码 发现我的value等价他的hash 他的初值是第一个单词的转换结果 而我的value竟然没初值 难怪运行错误。
明天继续:)