← 中文资源

简体中文版本

map 统计找出首个唯一字符

先用 map 统计每个 rune 的出现次数,再按原顺序复查,第一个计数为 1 的字符就是答案,返回其字节下标方便切片定位。

阅读英文原文

实现说明

逻辑集中在函数 firstUnique、main里。 for _, r := range s 反复执行,循环体之外没有别的重复。

使用要点

  • 执行文件,main 会按顺序走完 firstUnique。

常见问题

「map 统计找出首个唯一字符」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

签名一览:func firstUnique(s string) int

核心语句

for _, s := range []string{"devexamples", "aabb", "go-go"} {
	idx := firstUnique(s)
	if idx >= 0 {
		fmt.Printf("%s -> unique rune %q at index %d\n", s, rune(s[idx]), idx)
	} else {
		fmt.Printf("%s -> no unique rune\n", s)
	}
}
func firstUnique(s string) int {
	counts := make(map[rune]int)
	for _, r := range s {
		counts[r]++
	}
	for i, r := range s {
		if counts[r] == 1 {
			return i
		}
	}
	return -1
}

代码示例

package main

import "fmt"

// firstUnique 返回第一个只出现一次的 rune 的字节下标,没有则返回 -1
func firstUnique(s string) int {
	counts := make(map[rune]int)
	for _, r := range s {
		counts[r]++
	}
	for i, r := range s {
		if counts[r] == 1 {
			return i
		}
	}
	return -1
}

func main() {
	for _, s := range []string{"devexamples", "aabb", "go-go"} {
		idx := firstUnique(s)
		if idx >= 0 {
			fmt.Printf("%s -> unique rune %q at index %d\n", s, rune(s[idx]), idx)
		} else {
			fmt.Printf("%s -> no unique rune\n", s)
		}
	}
}