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

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

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

import java.util.Scanner;
import java.util.HashMap;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.nextLine();

        HashMap<Character, Integer> map1 = new HashMap<>();
        HashMap<Character, Integer> map2 = new HashMap<>();

        char[] chars = s.toCharArray();

        for (int i = 0 ; i < s.length() ; i++) {
            char ch = chars[i];
            map1.put(ch, map1.getOrDefault(ch, 0) + 1);
            if (map1.get(ch) == 1) {
                map2.put(ch, i);
            }
        }

        int min = Integer.MAX_VALUE;
        boolean bool = false;
        for (char c : map1.keySet()){
            if (map1.get(c) == 1){
                min = Math.min(map2.get(c),min);
                bool = true;
            }
        }

        if (bool){
            System.out.println(chars[min]);
        }else {
            System.out.println(-1);
        }


    }
}

主要是利用两个Map来分别存储字符出现的次数,字符第一次出现的位置

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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