每日一道算法题2021-10-25

104 阅读1分钟
JZ50 第一个只出现一次的字符
## 描述
在一个长为 字符串中找到第一个只出现一次的字符,并返回它的位置, 
如果没有则返回 -1(需要区分大小写).(从0开始计数)
数据范围:0≤n≤10000,且字符串只有字母组成。
要求:空间复杂度 O(n),时间复杂度 O(n)
public static int firstNotRepeatingChar(String str) {
    HashMap<Character, Integer> map = new HashMap<>();
    char [] ch = str.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        map.put(ch[i], map.getOrDefault(ch[i], 0)+1);
    }
    for (int i = 0; i < ch.length; i++) {
        if (map.get(ch[i]) == 1) {
            return i;
        }
    }
    return -1;


    for (int i = 0; i < str.length(); i++) {
        // 第一次出现和最后一次出现的位置一致
        while (str.indexOf(str.charAt(i)) == str.lastIndexOf(str.charAt(i))) {
            return i;
        }
    }
    return -1;
}