LeetCode题解(python)-3.无重复字符的最长子串
2019-03-01 20:53
706 查看
版权声明:转载请注明出处,谢谢 https://blog.csdn.net/zysps1/article/details/88068089
LeetCode题解(python)
3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
解决方法1:移动窗口
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: ls ={} max_ls = 0; i = 0; j = 0; count = 1 for sst in s: if sst in ls: i = max(i,ls[sst]) j = j+1 else: j = j+1; i = i; max_ls = max(max_ls,j-i) ls[sst] = count count = count+1 return max_ls
解题心得:
注意i和j是窗口的两边,i是左边,j一直在向右增加,i可不变或者增加,使用max让i不至于后退。
解决方法2:
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: ls ={} max_ls = 0; j = 0; for i in range(len(s)): if s[i] in ls: j = max(ls[s[i]],j) max_ls = max(max_ls,i-j+1) ls[s[i]] = i+1 return max_ls
解题心得:
看懂大神的代码,又自己分析重写的,利用了字典查找,i用来从前往后遍历,j用来标记最近重复字符的位置,i-j+1就是当前不重复字符串长度。
相关文章推荐
- LeetCode3. python实现:无重复字符的最长子串问题☆☆
- LeetCode 3. 无重复字符的最长子串 Python
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- Leetcode 3. 无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串
- 【Leetcode一刷】3.无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- [Leetcode] 3.无重复字符的最长子串
- Leetcode 刷题(python)之 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- leetcode之3. 无重复字符的最长子串python实现
- LeetCode 3. 无重复字符的最长子串
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- leetcode(三)—— Longest Substring Without Repeating Characters(最长不重复子串 Python/C++)
- leetcode 3:无重复字符的最长子串
- Leetcode每日一道 -- 无重复字符的最长子串
- 【LeetCode题目记录-3】字符串中最长的没有重复字符的子串
- LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
- 3.无重复字符的最长子串(Longest Substring Without Repeating Characters)
- 【LeetCode】第三题:无重复字符的最长子串