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.

          题目读起来很简单,一开始做的时候也很自信,但是提交了很多次都失败了。

          思路:

    1. 最长不重复子串,暴力方法就是遍历所有的子串,并检查是否有重复的子串,但是这种时间上复杂度很高,被pass
    2. 用dp[j]来表示子串0-j中最长不重复子串,那么则存在两种状态:
      • s[j]在start之后,j前面出现,此时dp[j] = j - start -1 (start 为s[j]之前最后出现的位置)
      • s[j]未出现,此时dp[j] = dp[j-1] + 1;
    3.  dp中最大的即为最长的不重复子串。
     1 class Solution:
     2     def lengthOfLongestSubstring(self, s):
     3         """
     4         :type s: str
     5         :rtype: int
     6         """
     7         dp = {-1:0}
     8         i = 0
     9         index = 0
    10         maxLen = 0;
    11         temp = {}
    12         for x in s:
    13             if(temp.get(x) != None and temp.get(x) >= index): #说明在start之后,j之前已经出现过,那么就重新开始计算。
    14                 index = temp.get(x) + 1
    15                 dp[i] = i - temp.get(x);
    16             else:
    17                 dp[i] = dp[i-1] + 1;
    18             temp[x] = i
    19             maxLen = max(dp[i],maxLen)
    20             i += 1
    21         return maxLen
    22        

         

  • 相关阅读:
    monkey事件简介
    Monkey简介
    Package与Activity简介
    adb 命令
    安卓模拟器简介
    iis重启的几种方法
    window下安装FTP服务器
    防止dedecms注入文件挂马的解决方法
    织梦漏洞可疑PHP文件/article文件夹
    织梦Dedecms系统可疑文件include/filter.inc.php扫描出漏洞,该如何解决?
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/8446625.html
Copyright © 2011-2022 走看看