一、创建
map 是类似于其他语言字典或者哈希表的东西,表现为 key-value
3 种声明方式
make
m:=make(map[int]string)
var
var m map[string]string
隐私声明
m = map[string]string{}
package main
import "fmt"
func main() {
m1 := map[string]string{
"name": "lulubin",
"course": "golang",
"site": "lulublog",
"quality": "notbad",
}
m2 := make(map[string]int) // m2 == empty map
var m3 map[string]int // m3 == nil
fmt.Println("m1=", m1);
fmt.Println("m2=", m2);
fmt.Println("m3=", m3);
}
二、获取
key 不存在时,获得 value 类型的初始值
用 value, ok:= m[key] 来判断是否存在 key
package main
import "fmt"
func main() {
m := map[string]string{
"name": "lulubin",
"course": "golang",
"site": "lulublog",
"quality": "notbad",
}
courseName := m["course"]
fmt.Println(`m["course"] =`, courseName)
if causeName, ok := m["cause"]; ok {
fmt.Println(causeName)
} else {
fmt.Println("key 'cause' does not exist")
}
}
三、删除
package main
import "fmt"
func main() {
m := map[string]string{
"name": "lulubin",
"course": "golang",
"site": "lulublog",
"quality": "notbad",
}
name, ok := m["name"]
fmt.Printf("m[%q] before delete: %q, %v\n", "name", name, ok)
delete(m, "name")
name, ok = m["name"]
fmt.Printf("m[%q] after delete: %q, %v\n", "name", name, ok)
}
四、遍历
使用 range 遍历 key,或者遍历 key, value 对
不保证遍历顺序,如需顺序,需手动对 key 排序
使用 len 获得元素个数
package main
import "fmt"
func main() {
m := map[string]string{
"name": "lulubin",
"course": "golang",
"site": "lulublog",
"quality": "notbad",
}
for k, v := range m {
fmt.Println(k, v)
}
}
五、map 的 key
map 使用哈希表,必须可以比较相等
除了 slice, map, function 的内建类型都可以作为 key
Struct 类型不包含上述字段,也可作为 key
六、例题
6.1、题目
寻找最长不含有重复字符的子串
示例 1:
输入:s = "abcabcbb"
输出:3
解释:因为无重复字符的最长子串是 "abc",所以其长度为 3
示例 2:
输入:s = "bbbbb"
输出:1
解释:因为无重复字符的最长子串是 "b",所以其长度为 1
示例 3:
输入:s = "pwwkew"
输出:3
解释:因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是子串的长度,"pwke" 是一个子序列,不是子串
示例 4:
输入:s = ""
输出:0
6.2、解题思路
对于每一个字母 x
lastOccurred[x] 不存在,或者< start →无需操作
lastOccurred[x] >= start >更新start
更新 lastOccurred[x],更新 maxLength
6.3、代码
package main
import "fmt"
func lengthOfNonRepeatingSubStr(s string) int {
lastOccurred := make(map[rune]int)
start := 0
maxLength := 0
for i, ch := range []rune(s) {
if lastI, ok := lastOccurred[ch]; ok && lastI >= start {
start = lastI + 1
}
if i-start+1 > maxLength {
maxLength = i - start + 1
}
lastOccurred[ch] = i
}
return maxLength
}
func main() {
fmt.Println(
lengthOfNonRepeatingSubStr("abcabcbb"))
fmt.Println(
lengthOfNonRepeatingSubStr("bbbbb"))
fmt.Println(
lengthOfNonRepeatingSubStr("pwwkew"))
fmt.Println(
lengthOfNonRepeatingSubStr(""))
fmt.Println(
lengthOfNonRepeatingSubStr("b"))
fmt.Println(
lengthOfNonRepeatingSubStr("abcdef"))
fmt.Println(
lengthOfNonRepeatingSubStr("这里是鲁鲁博客"))
fmt.Println(
lengthOfNonRepeatingSubStr("一二三二一"))
fmt.Println(
lengthOfNonRepeatingSubStr("黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"))
}