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

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    Java技术之ThreadLocal的使用
    find and find_by
    vim-config
    把字符串当做js代码执行的方法
    lodop打印设计
    前端使用lodop如何获取打印状态
    lodop第三方插件的使用
    nodejs中http服务器,如何使用GET,POST请求发送数据、npm、以及一些插件的介绍
    nodejs 用http模块搭建的服务器的路由,以及路由代码的重构过程
    nodejs基础 用http模块 搭建一个简单的web服务器 响应JSON、html
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8574132.html
Copyright © 2020-2023  润新知