Go基础之"寻找最长不含重复字母的字符串"(Map篇番外)

  • 解题思路:

 

对于每个字母"x":

  1.  lastOccurred[x]不存在或者<start       =>  无需操作
  2.  lastOccurred[x]>=start                      =>     更新start
  3. 更新lastOccurred[x],maxLength

程序实现 

package main

import (
    "fmt"
)

func lengthOfNonRepeatSubstr(s string) int {
    lastOccurred := make(map[byte]int)  //记录字串中出现的每个字符在字串中最后出现的位置
    maxLength := 0    //记录最长长度
    startIndex := 0   //记录字串的起始位置,即在整个字串的下标
    
    for i, ch := range []byte(s) {  
        if lastLocation, ok := lastOccurred[ch]; ok  && lastLocation >= startIndex {
            startIndex = lastLocation+1
        }
        if i-startIndex+1 > maxLength {
            maxLength = i-startIndex+1
        }
        lastOccurred[ch] = i    
    }
    return maxLength
}

func main(){
    fmt.Println(lengthOfNonRepeatSubstr("abccba"))
    fmt.Println(lengthOfNonRepeatSubstr(""))
    fmt.Println(lengthOfNonRepeatSubstr("abcde"))
    fmt.Println(lengthOfNonRepeatSubstr("a"))
    fmt.Println(lengthOfNonRepeatSubstr("aaaa"))   
}

测试结果:

3
0
5
1
1
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值