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

找出字符串中第一个只出现一次的字符(题面已经更新)

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

import java.util.*;

public class Main 
{
    private int count(String str)
    {
        Map<Character, Integer> map = new HashMap<>();
        for (char ch : str.toCharArray()) {
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }
        for (char ch : str.toCharArray()) {
            if (map.get(ch) == 1) {
                return ch;
            }
        }
        return -1;
    }

    public Main() 
    {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) 
        {
            String str = in.nextLine();
            int result = count(str);
            if (result == -1) {
                System.out.println(result);
            }
            else {
               System.out.println((char)result);
            }
        }
    }

    public static void main(String[] args) 
    {
        Main solution = new Main();
    }
}
全部评论
map不用保证输入顺序呀 他遍历的时候是遍历的原字符串 没有遍历map
5 回复 分享
发布于 2022-09-29 15:01 广东
使用HashMap无法保证输入顺序吧,得用LinkedHashMap
3 回复 分享
发布于 2022-08-10 19:36
老清新说的很好
2 回复 分享
发布于 2022-11-07 09:48 上海

相关推荐

评论
17
1
分享

创作者周榜

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