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


题目描述

  • 等级: 简单

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

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

思路

对于字符串和Hash表的考察。
首先遍历一遍字符串中字符,用Hash表存储字符与其出现的次数。
再遍历一遍字符串中的字符,当碰到第一个出现次数为1的字符时,返回响应的索引位置。
如果都没有,返回-1。

答案

func firstUniqChar(s string) int {
    count := map[int32]int{}
    for _, v := range s {
        oldCount := count[v]
        count[v] = 1   oldCount
    }
    for k, v := range s {
        if count[v]==1{
            return k
        }
    }
    return -1
}

结果

387.png


tencent.jpg
)

猜你喜欢

转载自www.cnblogs.com/clawhub/p/11974227.html