Files
LeetCode-Go/website/content/ChapterFour/0387.First-Unique-Character-in-a-String.md
2020-08-09 00:39:24 +08:00

875 B
Executable File

387. First Unique Character in a String

题目

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

题目大意

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

解题思路

  • 简单题,要求输出第一个没有重复的字符。

代码


package leetcode

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