• 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 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 }

     上面这个因为Unicode编码问题,它是不支持中文的,那go里面要怎么才能支持中文呢,这时候就要引出rune

    rune相当于go的char ,这里把byte改成rune

    package main
    
    import "fmt"
    
    
    func lengthOfNonRepeatinggSubStr( s string ) int {
        lastOccurred := make( map[rune]int)   //修改部分
        start := 0
        maxLength := 0
    
        for i, ch := range  []rune(s) {     //修改部分
            lastI ,ok := lastOccurred[ch]  //ok判断有没有key
            if ok && lastI >= start{
                start = lastI + 1
            }
            if i - start + 1 > maxLength{
                maxLength = i - start + 1
            }
            lastOccurred[ch] = i
        }
        return  maxLength
    }
    func main() {
        fmt.Println(lengthOfNonRepeatinggSubStr( "abcabccc"))  //3
        fmt.Println(lengthOfNonRepeatinggSubStr( "abcabdefgh"))  //6
        fmt.Println(lengthOfNonRepeatinggSubStr("我以为只要唱的用心良苦苦"))  //11
    
    }
  • 相关阅读:
    com.alibaba.fastjson.JSONException: default constructor not found. class ……
    ActiveMQ伪集群部署
    #{}和${}的区别
    微信小程序——报错汇总
    PHP——base64的图片的另类上传方法
    PHP——base64的图片转为文件图片
    veu——引入iconfont图标
    vue——script内容详解
    webpack——阮一峰webpackDemo分析
    webpack——快速入门【一】
  • 原文地址:https://www.cnblogs.com/yuxiaoba/p/9346107.html
一二三 - 开发者的网上家园