LeetCode每日一题:字符串中的第一个唯一字符(No.387)

584 阅读1分钟

题目:字符串中的第一个唯一字符


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

示例:


s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

思考:


两次循环,第一次循环记录每个字母出现的次数。
第二次循环,按字符串中字母顺序找到次数为1的第一个字母即可。

实现:


 class Solution {
    public int firstUniqChar(String s) {
        int[] letter = new int[26];
        for (char c : s.toCharArray())
            letter[c - 'a']++;
        for (int count = 0; count < s.length(); count++) {
            if (letter[s.charAt(count) - 'a'] == 1) return count;
        }
        return -1;
    }
}