今天开始刷leetcode,进行一个记录,写的比较简陋,见谅
Longest Substring Without Repeating Characters
Question:
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.
我自己写了一个方法,时间复杂度为o(n^2)
思路是这样的
start为开始位置
end为结束位置
s为输入的字符串
看第i个字符是否在字串s[start,end]之间存在
如果不存在将end向后移动一位,并计算其长的res = end-start
当存在时冲突时,将start更新到第i个字符在s[start,end]出现的位置,并将end向后移动一位
代码如下所示:
1 class Solution(object): 2 def lengthOfLongestSubstring(self, s): 3 start = 0 4 end = 0 5 temp = -1 6 res = 0 7 8 for i in range(len(s)): 9 for j in range(start,end): 10 if(s[j]==s[i]): 11 temp = j+1 12 if(temp == -1): 13 end += 1 14 res = max(res,end-start) 15 else : 16 start = temp 17 end += 1 18 temp = -1 19 return res
网上看了一个方法,很有意思,时间复杂度是o(n),首先参数m为一个列表,大小为256,可以根据ascii存放字符串中每个字符对应的位置
例如:'aAb'->m[97] = 0 , m[65] = 1,m[98]=2
res记录最大长度
start用于记录substring的起始位置
当s[i]第一次出现也就是m[ord(s[i])]==0
或者是s[i]多次出现,但是起始位置大于之前相同字符出现的位置的时候,对res进行更新
res = max(res,i-start+1)
反之更新start位置,将start更新到出现相同字符的位置上
1 class Solution(object): 2 def lengthOfLongestSubstring(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 m = [0]*256 8 res = 0 9 start = 0 10 for i in range(len(s)): 11 c = ord(s[i]) 12 if (m[c] == 0 or m[c]<start): 13 res = max(res,i+1-start) 14 else: 15 start = m[c] 16 m[c] = i+1 17 return res
参考资料:
[LeetCode] Longest Substring Without Repeating Characters 最长无重复子串
浙公网安备 33010602011771号