• 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        

         

  • 相关阅读:
    第二阶段冲刺第四天
    第二阶段冲刺第三天
    第二阶段冲刺第二天
    第二阶段冲刺第一天
    软件工程结对作业01(补充)
    软件工程概论个人总结
    梦断代码阅读笔记06
    梦断代码阅读笔记05
    构建之法阅读笔记04
    构建之法阅读笔记01
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/8446625.html
Copyright © 2020-2023  润新知