lastOccured := make(map[rune]int)创建是一个空map,怎么与lastOccured[ch]关联的?
来源:3-5 Map例题

白木轮
2020-06-22
前面我们学习到的make(map[rune]int)创建是一个空map,这里的lastOccured := make(map[rune]int)同样也是创建是一个空map?如果是创建是一个空map,怎么与lastOccured[ch]关联的?怎么把for i, ch := range []rune(s) 中的ch放到map lastOccured 的啊?
2回答
-
ccmouse
2020-06-23
请仔细参考上一节关于空map的讨论。go语言的map,即使值不存在,用[]也会返回“零”值。在本例中我们巧妙的运用了这个特点,使得程序非常精简
00 -
白木轮
提问者
2020-06-22
package main
import (
"fmt"
)
func lengthNoRepeatString(s string) int {
lastOccured := make(map[rune]int)
start := 0
maxlenth := 0
for i, ch := range []rune(s) {
fmt.Println(i, lastOccured[ch])
if lastI, ok := lastOccured[ch]; ok && lastI >= start {
//if lastOccured[ch] >= start {
start = lastI + 1
//start = lastOccured[ch] + 1
}
if i-start+1 > maxlenth {
maxlenth = i - start + 1
}
lastOccured[ch] = i
}
return maxlenth
}
func readMap(s string) {
m := make(map[rune]int)
//var max = 0
for i, ch := range []rune(s) {
fmt.Println(i, m[ch])
//max = m[ch]
}
//return max
}
func main() {
s := "wkfl0iklkjjjh"
a := lengthNoRepeatString(s)
fmt.Println(a)
readMap(s)
//fmt.Println(b)
}func lengthNoRepeatString(s) 中fmt.Println(i, lastOccured[ch])得到结果:
0 0
1 0
2 0
3 0
4 0
5 0
6 1
7 3
8 6
9 0
10 9
11 10
12 0
6
func readMap 中fmt.Println(i, m[ch]) 得到结果:
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 0
11 0
12 0
成功: 进程退出代码 0.
从上面结果看到 func readMap 中的map 都是0,而第一个func lengthNoRepeatString(s)是有值的,为什么?
00
相似问题