一天一道LeetCode(二)3. 无重复字符的最长子串
2019-03-29 22:15
274 查看
3. 无重复字符的最长子串
题目描述:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例:
示例 1:
输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:< 4000 /strong>
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
解题思路:
遍历字符串,并每次把字符丢入字典中{字符:索引},同时设置无重复子串头,尾指针,尾指针一直后移
- 当字符没有重复,头指针不动
- 当字符重复时, 重复字符前面没有重复字符,这个比较简单,直接将头指针设为集合中重复字符对应索引下一位即可; 如"abcbda"中的’b’
- 重复字符是上次重复字符前的字符,其索引没有被刷新过,它发生重复时需要把它的索引刷新到尾指针,如"abcbda"中的’a’
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: str_set = {} head = 0 end = 0 lenth = 0 for i in s: # 字符未重复 if i not in str_set: str_set[i] = end # 字符重复了 else: # 字符重复,且之前的记录未被刷新,相当于重复字符在串中间 if str_set[i] < head: str_set[i] = end # 字符重复,之前的记录刷新过,相当于重复字符在串头 else: head = str_set[i] + 1 str_set[i] = end if lenth <= end - head: lenth = end - head + 1 end += 1 return lenth
运行结果:
相关文章推荐
- LeetCode题目C++实现:3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- Leetcode(C++)——3. 无重复字符的最长子串
- Leetcode 3.无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- 【leetcode】3. 无重复字符的最长子串
- Leetcode刷题35-3.无重复字符的最长子串(C++)
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- LeetCode 3. 无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(Java)
- Leetcode——3.无重复字符的最长子串
- Leetcode每日一道 -- 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串 Python
- leetcode 3. 无重复字符的最长子串(Java 版)
- LeetCode3. python实现:无重复字符的最长子串问题☆☆
- 【Leetcode】3. 无重复字符的最长子串[未解出]
- LeetCode3. 无重复字符的最长子串(python)
- LeetCode-3.无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- 【leetcode每日一题】【2019-04-10】3.无重复字符的最长子串