Go map例题

 1 package main
 2 
 3 import "fmt"
 4 
 5 //map例题
 6 //寻找最长不含有重复字符的子串
 7 // abcabcbb  -> abc
 8 //pwwkew ->wke
 9 //对每一个字母x:
10 //   lastOccurred[x]不存在,或者< start -> 无需操作
11 //   lastOccurred[x] >= start -> 更新start
12 //   更新lastOccurred[x],更新maxLength
13 
14 func lengthOfNonRepeatinggSubStr( s string ) int {
15     lastOccurred := make( map[byte]int)
16     start := 0
17     maxLength := 0
18 
19     for i, ch := range  []byte(s) {
20         println(i)
21         lastI ,ok := lastOccurred[ch]  //ok判断有没有key
22         if ok && lastI >= start{
23             start = lastI + 1
24         }
25         if i - start + 1 > maxLength{
26             maxLength = i - start + 1
27         }
28         lastOccurred[ch] = i
29     }
30     return  maxLength
31 }
32 func main() {
33     fmt.Println(lengthOfNonRepeatinggSubStr( "abcabccc"))  //3
34     fmt.Println(lengthOfNonRepeatinggSubStr( "abcabdefgh"))  //6
35 
36 }

猜你喜欢

转载自www.cnblogs.com/yuxiaoba/p/9346107.html
今日推荐