zoukankan      html  css  js  c++  java
  • LeetCode——Problem3:Longest Substring Without Repeating Characters

    哎哟我天啊。这道题快折磨死我了。刚开始连题都没看明白,就是不知道substring是什么意思。研究了好长时间才看出来的。

    光辉历史呀。。。菜死了

    1、题目

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

    Example 1:Input: "abcabcbb"      Output: 3      Explanation: The answer is "abc", with the length of 3.
    Example 2:Input: "bbbbb"         Output: 1       Explanation: The answer is "b", with the length of 1.
    Example 3:Input: "pwwkew"     Output: 3        Explanation: 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.
     
    意思就是给一个字符串,找出最长的无重复子串。
    比如
    “abcabcbb”:他的无重复子串就是“abc”,“abc”,“b”
    “pwwkew”:它的无重复子串就是“pw”,“wke”,“kew”。最长的长度当然是3啦。而不是“pwke”。因为他要找的是子串,并不是要找的不重复序列。
    "dvdf":它的无重复子串就是“dv”,“vdf”
    说白了,就是一个字符一个字符的遍历,找出来没有重复字符的子字符串。
    只是为了看懂这个,就花了好多时间,菜死了。

    2、Python解法

    class Solution:
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            r=""   #储存无重复子串
            maxNum=0  #最大无重复子串的长度
            for i in s:
                if i not in r:           #如果不在子串里,就代表无重复,直接插进去
                    r=r+i
                else:                     #如果在子串里,就代表重复了,不能直接插进去
                    if len(r)>maxNum:maxNum=len(r)     #先算出来上一个子串的长度
                    r = r[r.index(i)+1:]+i          #把这个相同字符后面的保留。比如"dvdf"。第一个子串是"dv",再遍历到d的时候,需要把第一个d后面的v保留,再形成一个"vd"子串,这样还是无重复子串。不保留v的话,就不是一个完整的无重复子串了
            if len(r) > maxNum: maxNum = len(r)
            return maxNum
    
    s="dvdf"
    a=Solution()
    print(a.lengthOfLongestSubstring(s))
     我的解释代码里面写的很清楚。
    运行效果还不错

    C语言版的先不写了吧,我已经花了快两个小时了。按照这个思路写,完全没问题。

     
  • 相关阅读:
    从客户端(&)中检测到有潜在危险的 Request.Path 值。
    对访问修饰关键字public, protected, internal and private的说明
    C#综合揭秘——细说多线程(下)
    iis下配置:php+mysql
    工厂模式(Factory Patter)
    HDU 1040 As Easy As A+B [补]
    HDU 1020 Encoding
    HDU 1076 An Easy Task
    UVA 100 The 3n + 1 problem
    民大OJ 1668 追杀系列第二发
  • 原文地址:https://www.cnblogs.com/albert-yzp/p/9695107.html
Copyright © 2011-2022 走看看