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

113 阅读1分钟

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

示例 1:

输入: s = "leetcode"
输出: 0

示例 2:

输入: s = "loveleetcode"
输出: 2

 

示例 3:

输入: s = "aabb"
输出: -1

1.HashMap解法

class Solution {
    public int firstUniqChar(String s) {
        char[] chars=s.toCharArray();
       Map<Character,Integer> map=new HashMap<>();
        for(char i:chars){
            map.put(i,map.getOrDefault(i,0)+1);//没出现过的就返回0出现过的就返回ch对应的值
        }
        for(int j=0;j<s.length();j++){
             if (map.get(chars[j]) == 1) {//值为1的就是出现一次的
                return j;
            }
        }
        return -1;
           
    }
}

 

2.评论区自制HashMap

class Solution {
public:
    int firstUniqChar(string s) {
        int a[26]={0};
        int index[26];
        int size=s.size();
        for(int i=0;i<size;i++)
        {
            a[s[i]-'a']++;
            index[s[i]-'a']=i;
        }
        for(int i=0;i<size;i++)
        {
            if(a[s[i]-'a']==1)
            {
                return index[s[i]-'a'];
            }
        }
        return -1;
    }
};