LeetCode 无重复字符的最长子串
2018-04-27 11:21
239 查看
题目
给定一个字符串,找出不含有重复字符的最长子串的长度。
示例:
给定 “abcabcbb” ,没有重复字符的最长子串是 “abc” ,那么长度就是3。
给定 “bbbbb” ,最长的子串就是 “b” ,长度是1。
给定 “pwwkew” ,最长子串是 “wke” ,长度是3。请注意答案必须是一个子串,”pwke” 是 子序列 而不是子串。
我的题解
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ m = 0 tc = str() for c in s: if c not in tc: tc += c m = max(len(tc),m) else: tc+=c tc = tc[tc.index(c)+1:len(tc)+1] return m
解释
- 查找最长字串长度,假设最长字串长度为0,当输入字符串为”时,返回0即可。
- tc用来记录当前最长字符串(tc在遍历字符串后,可能包含的并非结果字串,但该题目只需要找出长度,并不需要记录子串)。
- 遍历原始字符串,得到字符c。
- 如果c没有在tc中,则把c添加到tc结尾位置上,并且修正最长字串长度。
- 如果该字符已经存在tc中,则照样把c添加到tc结尾位置上,并移除c所在位置前(包括c)的字符,组成新的字串。
结果
执行用时76ms,比80%的结果要快。由于python的字符串是immutable,每次修改tc都会产生新的字符串,主要耗时在这个地方。
阅读更多相关文章推荐
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- leetcode(3)无重复字符的最长子串
- Leetcode:395至少有K个重复字符的最长子串(C++)
- [LeetCode]3. Longest Substring Without Repeating Characters寻找最长无重复字符的子串
- leetcode 395. 至少有K个重复字符的最长子串
- LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
- Leetcode 刷题(python)之 无重复字符的最长子串
- leetcode:Longest Substring Without Repeating Characters (寻找最长无重复字符的子串)
- 【leetcode】第3题:求最长不重复(字符不重复)的子串的长度
- LeetCode: 3_Longest Substring Without Repeating Characters | 求没有重复字符的最长子串的长度 | Medium
- [leetcode]Longest Substring Without Repeating Characters【最长不重复字符子串】
- 无重复字符的最长子串 - LeetCode
- LeetCode 3 无重复字符的最长子串(哈希表或数组)
- LeetCode 3. Longest Substring Without Repeating Characters--不包含重复字符的最长子串长度
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- leetcode-最长无重复字符的子串
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- [leetcode]获取字符串中字符不重复的最长子串的长度
- LeetCode 3. 无重复字符的最长子串 Python