题目
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
- 遍历字符串,将字符串中的字符放入map中,字符第一次出现,值为字符所在位置,字符再次出现,值为字符串长度(也可以其他较大值)
- 遍历map,寻找位置最小值minPos
- 如果minPos等于字符串长度,说明所有字符都重复,返回-1,否则minPos即为所求第一个非重复字符的位置
代码
findUniqueChar.go
package _387_First_Unique_Character_String
import "fmt"
func FirstUniqChar(s string) int {
len1 := len(s)
if 0 == len1 {
return -1
}
var charMap map[byte]int
charMap = make(map[byte]int)
for i := 0; i < len1; i++ {
_, ok := charMap[s[i]]
if ok {
charMap[s[i]] = len1
} else {
charMap[s[i]] = i
}
}
fmt.Printf("map:%+v\n", charMap)
var minPos int
minPos = len1
for _, v := range charMap {
if minPos > v {
minPos = v
}
}
if len1 == minPos {
return -1
}
return minPos
}
测试
findUniqueChar_test.go
package _387_First_Unique_Character_String
import "testing"
func TestFirstUniqChar(t *testing.T) {
var tests = []struct{
intput string
output int
}{
{"loveleetcode", 2},
{"", -1},
{"cc", -1},
}
for _, test := range tests {
ret := FirstUniqChar(test.intput)
if ret == test.output {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", test.output, ret)
}
}
}