哈希表刷题总结
- 1002. 查找共用字符(计数法,数组优化哈希)
- 1370. 上升下降字符串(计数法,数组优化哈希)
1002. 查找共用字符(计数法,数组优化哈希)
class Solution {
public List commonChars(String[] words) {
// 使用int数组替代哈希表 26代表字母个数
int [] res = new int[26];
// 初始化res,这里调用了字符串的api,toCharArray(),转换为了字符数组
for(char c:words[0].toCharArray()){
// 字符对应位置计数
res[ c - 'a']++;
}
// 遍历余下的字符串
for(int i = 1; i < words.length; i++){
// 定义一个临时数组
int[] temp = new int[26];
// 遍历字符串中的字符
for(char c : words[i].toCharArray()){
// 储存到临时数组中
temp[c - 'a']++;
}
// 对数组26个字母位置个数,取交集
for(int j = 0; j < 26; j++){
res[j] = Math.min(res[j],temp[j]);
}
}
List ans = new ArrayList<>();
// 筛选出个数大于0的字符出来
for(int i = 0; i < 26; i++){
if(res[i] > 0){
// 输出字符,这里要主要有可能有重复的字符需要输出
for(int j = 0; j < res[i]; j++){
ans.add((char)(i+'a')+"");
}
}
}
return ans;
}
}
1370. 上升下降字符串(计数法,数组优化哈希)
class Solution {
public String sortString(String s) {
// 定义一个26个字母的计数数组
int[] counts = new int[26];
for(char c:s.toCharArray()){
// 对应位置 储存个数
counts[ c - 'a']++;
}
// 使用StringBuild来动态拼接字符串
StringBuilder sb = new StringBuilder();
// 遍历原始数组
while(sb.length() < s.length()){
// 字符先上升(正序)
for(int i = 0; i < 26; i++){
if(counts[i] > 0){
// 储存进sb
sb.append((char)(i + 'a'));
// 对应个数-1
counts[i]--;
}
}
// 字符后下降(倒序)
for(int i = 25; i >= 0; i--){
if(counts[i] > 0){
// 储存进sb
sb.append((char)(i + 'a'));
// 对应个数-1
counts[i]--;
}
}
}
// 返回结果
return sb.toString();
}
}