leetcode387-字符串中的第一个唯一字符

原题

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.
 

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

解法

思想

遍历两次数组,第一次将字母和出现的次数放在哈希表中对应起来,第二遍找出哈希表中值为1的字母。

代码

class Solution {
    public int firstUniqChar(String s) {
        Map<Character,Integer> map = new HashMap<>();
        int n = 0;
        char[] chars = s.toCharArray();
        for(char i:chars){
            if(map.containsKey(i)){
                map.put(i,map.get(i)+1);
            }else{
                map.put(i,1);   
            }
            n++;
        }
        n = 0;
        for (char i:chars) {
            if(map.get(i)==1) return n;
            n++;
        }
        return -1;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode387-%e5%ad%97%e7%ac%a6%e4%b8%b2%e4%b8%ad%e7%9a%84%e7%ac%ac%e4%b8%80%e4%b8%aa%e5%94%af%e4%b8%80%e5%ad%97%e7%ac%a6/

发表回复

登录后才能评论