找出字符串中第一個只出現一次的字符

題目描述

找出字符串中第一個只出現一次的字符

輸入描述

輸入一串字符

輸出描述

輸出一個字符

輸入例子

asdfasdfo

輸出例子

o

算法實現

import java.util.*;


public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.nextLine();
            System.out.println(findFirst(input));
        }

        scanner.close();
    }

    private static char findFirst(String s) {

        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            // 若是已經出現過就標記爲無效
            if (map.containsKey(c)) {
                map.put(c, Integer.MAX_VALUE);
            } else {
                // 標記第一次出現的下標
                map.put(c, i);
            }
        }


        Collection<Integer> set = map.values();
        int min = Integer.MAX_VALUE;
        // 找最小的下標
        for (int i : set) {
            if (min > i) {
                min = i;
            }
        }

        return min == Integer.MAX_VALUE ? '.' : s.charAt(min);
    }
}
相關文章
相關標籤/搜索