LeetCode-Q3-Longest Substring Without Repeating Characters
来源:互联网 发布:如何用c语言编写程序 编辑:程序博客网 时间:2024/06/11 12:15
- 自己思路
建立两个指针,外循环为首指针,内循环为尾指针,从左至右检查,每次尾指针右移将无重复字符子串存入maxlength变量,循环结束输出。
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ maxlen = 0 for i in range(len(s)): for j in range(len(s)): if s[j] not in s[i:j]: maxlen = max(maxlen,j-i+1) else: break return maxlen
问题
时间复杂度为O(n2)参考Discuss
建立字典进行已查询字符存储,利用字典的查询时间复杂度O(n)的特点,减小时间复杂度。代码
class Solution: # @return an integer def lengthOfLongestSubstring(self, s): start = maxLength = 0 usedChar = {} for i in range(len(s)): if s[i] in usedChar and start <= usedChar[s[i]]: start = usedChar[s[i]] + 1 else: maxLength = max(maxLength, i - start + 1) usedChar[s[i]] = i return maxLength
- 总结
对于需要检查元素在序列中重复问题,可利用字典来进行成员资格检查,减少时间复杂度。
0 0
- Leetcode Q3:Longest Substring Without Repeating Characters
- [LeetCode]Q3. Longest Substring Without Repeating Characters
- LeetCode-Q3-Longest Substring Without Repeating Characters
- [leetcode Q3] —— Longest Substring Without Repeating Characters
- leetCode Q3:Longest Substring Without Repeating Characters(java)
- 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
- Git学习笔记
- 委托(五):多播委托
- [leetcode]309. Best Time to Buy and Sell Stock with Cooldown
- HDU1215:七夕节(简单数论)
- 博弈论一般性解法总结
- LeetCode-Q3-Longest Substring Without Repeating Characters
- eclipse UML 学习 Rose
- (转)23种设计模式(4):建造者模式(实例代码并不怎么好)
- 交换与路由知识点总结(四)
- UVa 10118 Free Candies (记忆化搜索+状态压缩)
- Json安全
- mysql linux 安装和使用
- 创建Action的两种方式Spring和Struts
- Hibernate探索之路(一)——简介