Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【字符串中的第一个唯一字符】解法有问题 #44

Open
vivia1994 opened this issue Jun 17, 2021 · 2 comments
Open

【字符串中的第一个唯一字符】解法有问题 #44

vivia1994 opened this issue Jun 17, 2021 · 2 comments

Comments

@vivia1994
Copy link

image

@dingweihua
Copy link

我也验证了一下,确实有问题。

"aabb"在第二次遍历的时候,遍历到第二个a时,前后两个index相等,此时就返回了错误的index = 1

@dingweihua
Copy link

附上一段正确的逻辑:

func firstUniqueLetter(s string) int {
	var charArr [26]int
	for i, v := range s {
		arrIndex := v - 'a'
		if charArr[arrIndex] == 0 {
			// 这里的index + 1和默认的0区分开
			// -1 char有重复,0 初始化,>0 唯一的index
			charArr[arrIndex] = i + 1
		} else {
			charArr[arrIndex] = -1
		}
	}

	index := -1
	for _, v := range charArr {
		// >0 的值为唯一的index,同时获取到最小的index
		if v > 0 && (index == -1 || v-1 < index) {
			index = v - 1
		}
	}

	return index
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants