【leetcode】3. 无重复字符的最长子串
2019-01-22 15:39
281 查看
版权声明:https://github.com/linshuang/full-stack https://blog.csdn.net/qq83833224/article/details/86595447
题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
输入示例:
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
思路
- 设置iii和jjj为0,
- 从字符串头部向后逐步移动jjj,重复以下步骤
- 计算第jjj个元素在子串s[i:j]s[i:j]s[i:j]中的位置pospospos
- 位置pospospos不为-1,则更改iii为pos+1+ipos+1+ipos+1+i,如此s[i:j]s[i:j]s[i:j]保持了无重复字符的特性
- 否则比较s[i:j]s[i:j]s[i:j]与当前最长子串的长度,并尝试更新最长子串
代码
def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ i = j = 0 longest = 0 for j in range(0, len(s)): idx = s[i:j].find(s[j]) if idx >= 0: i = idx + 1 + i continue if (j - i + 1) > longest: longest = (j - i + 1) return longest
参考
- [1] leetcode原题
- [2] 详尽源码
相关文章推荐
- LeetCode3. 无重复字符的最长子串(python)
- LeetCode题目C++实现:3. 无重复字符的最长子串
- 【Leetcode】3. 无重复字符的最长子串[未解出]
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- Leetcode刷题35-3.无重复字符的最长子串(C++)
- Leetcode 3. 无重复字符的最长子串
- LeetCode3. python实现:无重复字符的最长子串问题☆☆
- LeetCode3. 无重复字符的最长子串(Java)
- 【Leetcode一刷】3.无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- LeetCode题解(python)-3.无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串 Python
- Leetcode(C++)——3. 无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串(Java 版)
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- [Leetcode] 3.无重复字符的最长子串