Java implements the first character that occurs only once

Find the first character that occurs only once in a string (1<=string length<=10000, all uppercase letters), and return its position.

code

     public static Character firstAppearChar(String str) {
        if (Strings.isNullOrEmpty(str)) {
            throw new IllegalArgumentException("str is null or empty.");
        }
        int length = str.length();
        if (length > 10000) {
            throw new IllegalArgumentException("str is too long.");
        }
        if (length == 1) {
            return str.charAt(0);
        }
        Map<Character, Integer> map = new HashMap<>(length);
        for (int i = 0; i < length; i++) {
            Character c = str.charAt(i);
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }
        for (int i = 0; i < length; i++) {
            Character c = str.charAt(i);
            if (map.get(c) == 1) {
                return c;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        Character c = firstAppearChar("abaccdeff");
        System.out.print(c);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325939897&siteId=291194637