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

作者: youzhihua | 来源:发表于2020-03-14 12:23 被阅读0次

    题目描述

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

    示例

    s = "leetcode"
    返回 0.
    
    s = "loveleetcode",
    返回 2.
    

    注意事项

    您可以假定该字符串只包含小写字母。

    思路

    1. 可以使用一个数组记录每个字符出现的次数。

    2. 既然只有小写字母,所以只需要26个空间便够用了。

    3. 先遍历一次字符串,然后记录每个字符出现的次数。

    4. 再从头遍历一次字符串,若该位置的元素只出现一次,返回该索引即可。

    Java代码实现

    class Solution {
        public int firstUniqChar(String s) {
            //由于只包含小写字母,所以26就够用了
            char[] chars = new char[26];
    
            for (int i = 0; i < s.length(); i++) {
                chars[s.charAt(i) - 'a']++;
            }
    
            for (int i = 0; i < s.length(); i++) {
                if(chars[s.charAt(i)-'a'] == 1){
                    return i;
                }
            }
    
            return -1;
        }
    }
    

    Golang代码实现

    func firstUniqChar(s string) int {
        chars := make([]int16,26)
        for i:=0; i<len(s);i++ {
            chars[s[i]-'a']++
        }
    
        for i:=0; i<len(s); i++{
            if chars[s[i] - 'a'] == 1{
                return i
            }
        }
        return -1
    }
    

    相关文章

      网友评论

        本文标题:字符串中的第一个唯一字符

        本文链接:https://www.haomeiwen.com/subject/dkevshtx.html