随笔 - 246  文章 - 0  评论 - 2  阅读 - 18454

面试题50. 第一个只出现一次的字符

复制代码
package leetcode;

import java.util.HashMap;
import java.util.HashSet;

public class offer_50 {
    
    
    public char firstUniqChar1(String s) {        
        HashSet<Character>set=new HashSet<Character>();
        
        //如果存在相同的字符用空格代替
        for(int i=0;i<s.length();i++) {
            if(!set.contains(s.charAt(i))) {
                set.add(s.charAt(i));
            }else {
                s=s.replace(s.charAt(i), ' ');
            }
            
        }
        
        //找出第一个非空格的字符
        for(int i=0;i<s.length();i++) {
            if(s.charAt(i)!=' ') {return s.charAt(i);}
        }
        return ' ';
    }
    
    
    public char firstUniqChar2(String s) {        
        HashMap<Character, Integer> map=new HashMap<Character, Integer>();
        
        //将每个字符和其数量存入map 集合中
        for(int i=0;i<s.length();i++) {
            int count=1;
            if(map.containsKey(s.charAt(i))) {
                count=count+1;
            }
            map.put(s.charAt(i), count);
        }
        
        //找出集合中value第一个为1的字符
        for(int i=0;i<s.length();i++) {
            if(map.get(s.charAt(i))==1) {return s.charAt(i);}
        }
        return ' ';
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        offer_50 off=new offer_50();
        System.out.println(off.firstUniqChar1("aabccdeffb"));
    }

}
复制代码

 

posted on   一仟零一夜丶  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示