• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
Longest substring without duplication

refer to: https://www.algoexpert.io/questions/Longest%20Substring%20Without%20Duplication

Problem Statement

 

 Analysis

 

 Code

def longestSubstringWithoutDuplication(string):
    # Write your code here.
    lastSeen = {}# hashmap to store the index of the lastSeen character(updated index of unique character)
    longest = [0,1] # initialize to itself (since in python the slice function will exclude the right range)
    startIdx = 0 # startIdx to traverse the whole string, update the start character in substring
    for i, char in enumerate(string):
        if char in lastSeen: # duplicate will occur if do nothing
            startIdx = max(startIdx, lastSeen[char] + 1) # update the startIdx, lastSeen character idx + 1 to exclude the lastSeen character
        if longest[1] - longest[0] < i + 1 - startIdx: #update the longest substring
            longest = [startIdx, i + 1] # the i+1 th character will be excluded
        lastSeen[char] = i # update the index of the lastSeen character
    return string[longest[0] : longest[1]]

Time and space complexity

 

 

 

 

 
posted on 2021-06-02 02:21  LilyLiya  阅读(45)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3