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
}

结果

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


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

相关文章:

  • 2022-12-23
  • 2021-09-01
  • 2022-03-06
  • 2021-06-28
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-26
  • 2021-06-30
  • 2022-12-23
  • 2021-08-08
  • 2022-01-28
  • 2021-10-12
  • 2022-01-03
相关资源
相似解决方案