LeetCode 387 字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

示例:
若 s = “leetcode”
返回 0

若 s = “loveleetcode”
返回 2

Java求解,基本思路就是两次遍历,第一次统计各个字符的个数,第二次找出第一个唯一的字符

解法一:使用一个count[26]数组来表示各个字符出现的次数,每一个位置对应一个字母(所以是26)。比较巧妙

public int firstUniqChar(String s) {
    int count[] = new int[26];
    char[] chars = s.toCharArray();
    //先统计每个字符出现的次数
    for (int i = 0; i < s.length(); i++)
        count[chars[i] - 'a']++;
    //然后在遍历字符串s中的字符,如果出现次数是1就直接返回
    for (int i = 0; i < s.length(); i++)
        if (count[chars[i] - 'a'] == 1)
            return i;
    return -1;
}

解法二:使用HashMap
其中使用到了getOrDefault(key,default)函数,意思是"HashMap中如果有这个key,就返回对应的value;否则返回设置的default参数"

public int firstUniqChar(String s) {
    Map<Character, Integer> map = new HashMap();
    char[] chars = s.toCharArray();
    //先统计每个字符的数量
    for (char ch : chars) {
        map.put(ch, map.getOrDefault(ch, 0) + 1);
    }
    //然后在遍历字符串s中的字符,如果出现次数是1就直接返回
    for (int i = 0; i < s.length(); i++) {
        if (map.get(chars[i]) == 1) {
            return i;
        }
    }
    return -1;
}

解法三:使用indexOf()和lastIndexOf()
indexOf()从前往后查找字符,lastIndexOf()从后往前查找,所以当两个函数返回的下标相等时,该字符只出现了一次。这样代码虽然简单,但是时间复杂度会比较高。

    public int firstUniqChar(String s) {
        for (int i = 0; i < s.length(); i++)
            if (s.indexOf(s.charAt(i)) == s.lastIndexOf(s.charAt(i)))
                return i;
        return -1;
    }

感谢此链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/?discussion=6TyKA7

上一篇:Day6-----Python的序列类(有子类:元组类,列表类)


下一篇:151. 翻转字符串里的单词