Longest Substring Without Repeating Character…
2018-06-18 00:42:13来源:未知 阅读 ()
今天开始刷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 最长无重复子串
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- PostgreSQL在Update时使用Substring函数截取字符串并且加上C 2018-06-17
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
