栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

哈希表总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

哈希表总结

哈希表刷题总结
  • 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();


    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/306343.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号