zoukankan      html  css  js  c++  java
  • 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)

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    Neo4j自定义主键策略
    spring cloud Alibaba nacos 整合Neo4j pom 配置
    spring cloud Alibaba nacos 整合Neo4j配置
    若依前端 devtool source-map设置
    基于draw.io的二次开发,文件增加本地以及oss存储
    十多年来从三个容器管理系统中吸取的教训
    java8 CompletableFuture,allOf多实例返回
    CompletableFuture 使用详解
    使用CompletableFuture实现业务服务的异步调用
    [转]uni-app开发踩坑之路之this指向问题
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8574132.html
Copyright © 2011-2022 走看看