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

nunca

但行好事 莫问前程
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

LeetCode 第三题:Longest Substring Without Repeating Characters

一、题目

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

二、思路

从左往右依次遍历字符串s,如果不在子串substr中,则加入,如果item在substr中,首先判断目前的子字符串的长度是否为当前最长,然后我们思考下一个子字符串应该是从重复的这个字符的下一个开始的,因为如果在这个字符之前那么必然还是会遇见重复的item的。全部遍历后 判断当前长度是否为最长。 

遍历字符串每个字符:

       若字符不在子串substr中:

               substr加入此字符;

       若字符在子串substr中:

               if 当前 substr 当前子字符串最长:

                        当前的字符串长度付给变量 longestlenth

               else(当前的子字符串 substr 并不是最长):

                       当前项item加入到substr中

                       并且删除当前子串中第一次重复出现的字符,从此字符的一下位开始

循环遍历到最后,若len(substr) > longestlenth,则:

       longestlenth = len(substr)

return longestlenth

#coding:utf-8
def lengthOfLongestSubstring(s):
    """
    :type s: str
    :rtype: int
    """

     # s为空的情况
    if not s:
        return 0
    longestlenth = 1 # 非空子字符串的长度最小为1
    substr = "" # 子字符串
    for item in s:
        if item not in substr:
            substr += item
        else:
            if len(substr) > longestlenth:
                longestlenth = len(substr)
            # 应该从重复的下一个字符开始继续判断
            substr += item
            substr = substr[substr.index(item)+1:]
    if len(substr) > longestlenth:
        longestlenth = len(substr)
    return longestlenth

    """
    :type s: str
    :rtype: int
    
    maxlength = 0
    length = 0
    substring = []
    for i in s:
      try:
          index = substring.index(i)
          substring = substring[index+1:]
          substring.append(i)
          maxlength = max(maxlength, length)
          length = length - index
      except ValueError:
          substring.append(i)
          length += 1
          maxlength = max(maxlength, length)
    return maxlength
    """
if __name__ == '__main__':
    print(lengthOfLongestSubstring("abcabcbb"))

(来源:http://blog.csdn.net/iwanthn/article/details/54670292#t5)

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢

posted on 2018-03-15 16:03  乐晓东随笔  阅读(140)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3