题解 | #找出字符串中第一个只出现一次的字符#

找出字符串中第一个只出现一次的字符

http://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str = sc.next();
            Map<Character, Integer> map = new LinkedHashMap<>();
            for (int i = 0; i < str.length(); i++) {
                if(map.containsKey(str.charAt(i))){
                    map.put(str.charAt(i),map.get(str.charAt(i)) + 1);
                }else{
                    map.put(str.charAt(i), 1);
                }
            }
            char ch = 0;
            for(Map.Entry<Character,Integer> entry : map.entrySet()){
                if(entry.getValue() == 1){
                    ch = entry.getKey();
                    break;
                }
            }
            if(ch == 0){
                System.out.println(-1);
            }else{
                System.out.println(ch);
            }
        }
    }
}
全部评论
这样不行的,map里的key会自动排序,你遍历出现的次数是否为一的时候,第一个输出的值不一定是原字符串中第一个出现次数为1的字符
点赞 回复 分享
发布于 2022-03-28 21:28
思路很不错,学习了
点赞 回复 分享
发布于 2022-02-17 15:32

相关推荐

点赞 评论 收藏
分享
评论
4
4
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务