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        

         

  • 相关阅读:
    php过滤表单提交的html等危险代码
    浅析php过滤html字符串,防止SQL注入的方法
    PHP简单判断手机设备的方法
    如何用Math.max.apply()获取数组最大/小值
    Ubuntu14.04升级到Ubuntu16.04
    4、python数据类型之列表(list)
    3、python数据类型之字符串(str)
    centos7网卡名称修改以及配置
    rsync简单总结
    8、kvm虚拟机添加硬盘
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/8446625.html
Copyright © 2011-2022 走看看