力扣(LeetCode)字符串中的第一个唯一字符 个人题解

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

 

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

 

 

这题的思想还是比较简单明了的,通过hashmap记录所有的键值对应关系,即字符出现的次数,然后再回过头循环一遍来判断出现的次数是否符合题意。

要循环两次,空间和时间上都差强人意,但是是比较清晰的办法。

而且通过评论区的提醒,当字符串足够长且出现的重复次数比较集中时,这种方法反而会带来空间和时间上的优势。

 

代码如下:

import java.util.HashMap;

class Solution {
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<s.length();i++)
        {
            Character character=s.charAt(i);
            if(map.get(character)==null)
                map.put(character, 1);
            else
                map.put(character, map.get(character)+1);
        }
        for(int i=0;i<s.length();i++)
        {
            Character character=s.charAt(i);
            if(map.get(character)==1)
                return i;
        }
        return -1;
    }
}

 

posted @ 2019-02-25 21:22  AXiangCoding  阅读(175)  评论(0编辑  收藏  举报