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

问题描述

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

示例

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事项:您可以假定该字符串只包含小写字母。

思路

把字符串中的内容维护到一个hashMap中,对出现的次数进行计数。
然后遍历字符串,把第一个在hashMap中计数为1的字符的下标返回即可。

AC代码

class Solution {
    public int firstUniqChar(String s) {
        int[] arr = new int[26];
        char[] chars = s.toCharArray();
        for(char c:chars){
            arr[c-'a']++;
        }
        for(int i = 0; i < chars.length; i++){
            if(arr[chars[i]-'a'] == 1){
                return i;
            }
        }
        return -1;
    }
}
发布了396 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41687289/article/details/104914800