Java 实现第一个只出现一次的字符

在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符,并返回它的位置。

代码

     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);
    }

猜你喜欢

转载自blog.csdn.net/zl18310999566/article/details/80225232