[Leetcode]Longest Substring Without Repeating Characters
来源:互联网 发布:银行叫号机 淘宝 编辑:程序博客网 时间:2024/06/04 23:36
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
求没有重复字符的最长字符串~维护两个指针start, end;保证两个指针间没有重复元素,用hashmap判断是否有重复元素,如果end指针遇到了重复元素,把start指针往后移到第一个和end指针相同的字符之后(注意移动时要记得把start指针原来所在的位置及移动后的位置之间的元素从dictionary中删除掉)~代码如下,时间复杂度为O(n)
class Solution: # @return an integer def lengthOfLongestSubstring(self, s): if s is None or len(s) == 0: return 0 res = 0; dict = {} start, end = 0, 0 while end < len(s): if s[end] in dict: tmp = dict[s[end]] for i in xrange(start, dict[s[end]] + 1): del dict[s[i]] start = tmp + 1 else: res = max(res, end - start + 1) dict[s[end]] = end end += 1 return res
代码还可以再简洁一点~下面的代码就省去了从dict中删除前面重复元素之前的元素的步骤,所以效率也就更高~~Runtime 也从150ms左右降低到90ms~
class Solution: # @return an integer def lengthOfLongestSubstring(self, s): if s is None or len(s) == 0: return 0 dict = {}; start = 0; maxLen = 0 for end in xrange(len(s)): if s[end] in dict and dict[s[end]] >= start: start = dict[s[end]] + 1 dict[s[end]] = end maxLen = max(maxLen, end - start + 1) return maxLen
0 0
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- 【android】descendantFocusability属性在ListView中的妙用
- 算法时间复杂度
- hbase 异常 未解决
- 思量+实践
- DOM树中的Node(节点)与Element(元素)的区别
- [Leetcode]Longest Substring Without Repeating Characters
- 火影忍者的“忍术”,测试也能用?YES!
- 抽象类和接口
- iOS开发下载文件速度计算
- mongodb 的用户管理
- Couldn't load gdx from loader dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/ 错误
- objc_object 、objc_class、metaclass
- 房屋风水学整理
- java 导出word几种方法总结