majianyu
2/23/2019 - 2:06 PM

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

对字母 a 到 z 进行遍历,求每一个字母的 left index 和 right index 如果 left index 不为-1,并且 left index 等于 right,说明是唯一字符

提前声明 res 变量为-1,如果 res 为-1 或者大于 left index,则对 res 进行赋值

return res

func firstUniqChar(s string) int {
	res := 1<<63 - 1
	for c := 'a'; c <= 'z'; c ++ {
		left := strings.Index(s, string(c))
		right := strings.LastIndex(s, string(c))
		if left >= 0 && left == right {
			if res > left {
				res = left
			}
		}
	}
	if res == 1<<63-1 {
		return -1
	}
	return res
}