第一个只出现一次的字符

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)

两种解法

1.Map的key值不会重复 可以用来记录出现次数
public int firstNotRepeatingChar(String str) {
    int index = -1;
    Map<String, Integer> map = new HashMap<String, Integer>();
    if (str.length() > 0) {
        int len = str.length();
        for (int i = 0; i < len; i++) {
            if (null == map.get(str.charAt(i) + "")) {
                map.put(str.charAt(i) + "", 1);
            } else {
                int value = map.get(str.charAt(i) + "");
                map.put(str.charAt(i) + "", ++value);
            }
        }
        for (int i = 0; i < len; i++) {
            if (1 == map.get(str.charAt(i) + "")) {
                index = i;
                break;
            }
        }
    }
    return index;
}
2.时间复杂度最小 直接for循环 某个字符,左边没有出现 右边也没有出现 就是唯一的
public int firstNotRepeatingChar(String str) {
    int index = -1;
    if (str.length() > 0) {
        int len = str.length();
        for (int i = 0; i < len; i++) {
            Boolean left = str.substring(0, i).contains(str.charAt(i) + "");
            Boolean right = str.substring(i + 1, len).contains(str.charAt(i) + "");
            if (!left && !right) {
                index = i;
                break;
            }
        }
    }
    return index;
}
posted @ 2018-11-24 21:19  Aurora_wen  阅读(121)  评论(0编辑  收藏  举报