leetcode_哈希表原理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jt102605/article/details/84579619

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

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

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

      思路一:由于字符串自包含26个小写字母,所以可以开辟一个空间为26的数组,用来记录给个字母出现的频次 

class Solution {
    public int firstUniqChar(String s) {
        int[] freq = new int[26];
        
        //遍历字符串,记录字符串中每个字符出现的频次
        for(int i = 0; i<s.length(); i++){
            freq[s.charAt(i)-'a']++;
        }
        
        //遍历字符串,找出第一个出现频次为1的字符
        for(int i = 0; i<s.length(); i++){
            if(freq[s.charAt(i)-'a'] == 1){
                return i;
            }
        }
        
        return -1;
    }
}

猜你喜欢

转载自blog.csdn.net/jt102605/article/details/84579619