首页 > 编程语言 > 详细

算法-最大不重复子串Go+python

时间:2020-05-19 18:46:28      阅读:50      评论:0      收藏:0      [点我收藏+]

最大不重复子串是经典的滑动窗口问题

思路:
mp记录每个字符出现的最大索引位置
start记录当前不重复子串的起始索引位置

先用Python实现一遍

def lengthOfLongestSubstring(s: str) -> int:
    if len(s) <= 1: return len(s)
    mp, start, res = {}, 0, 0
    for i, v in enumerate(s):
        if v in mp and mp[v]>=start:
            start = mp[v]+1
        mp[v] = i
        res = max(res, i-start+1)
    return res

完全相同的思路再用Go实现一遍

func lengthOfLongestSubstring(s string) int {
    if len(s) <= 1 {return len(s)}
    mp := make(map[rune]int)
    start, res := 0, 0
    for i, v := range s {
        if _, ok := mp[v]; ok && mp[v] >= start {
            start = mp[v] + 1
        }
        mp[v] = i
        if i-start+1 > res {
            res = i-start+1
        }
    }
    return res
}

leetcode结果如下 (Python总是被碾压, 哭)
技术分享图片

算法-最大不重复子串Go+python

原文:https://www.cnblogs.com/chendongblog/p/12918344.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!