LeetCode3. python实现:无重复字符的最长子串问题☆☆
2019-02-26 20:34
676 查看
目录
问题
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
[code]输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
[code]输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
[code]输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 !!请注意,你的答案必须是 子串 的长度,"pwke"是一个子序列,不是子串。
题外话:拿到这个题的第一反应,正好是自己最近看过的哈希算法的用途,所以立刻就想到了解题思路。
解题思路
如题外话所言,正好是哈希算法的用武之地。通过字典,来存储不重复的子串,键为字符,值为对应的位置。再设置两个变量,一个变量result存储记录的最长子串的长度,一个变量temp记录当前子串的最长长度,如果temp>result,则result=temp。刚好遍历一遍字符串即可得到答案。代码实现具体如下:
python具体实现
[code]class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ strDict = {} # 字典存储当前子串 result = 0 # 存在最长子串长度 temp = 0 # 存储当前子串的长度 for i in range(len(s)): if s[i] not in strDict.keys(): strDict[s[i]] = i temp = temp+1 #else s[i] in strDict.keys(): else: # 有字符在字典中,故选取大于对应字符对应的值到当前值得字典中的值。 strDict = {key: value for key, value in strDict.items() if value > strDict[s[i]]} temp = len(strDict)+1 # tips:这是一处容易忽略的地方,为何要加1:因为还有当前的字符,也要算呀 strDict[s[i]] = i if temp>result: result = temp return result
相关文章推荐
- LeetCode 3. 无重复字符的最长子串 Python
- LeetCode 3. 无重复字符的最长子串
- 【Leetcode一刷】3.无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- Leetcode 刷题(python)之 无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- Leetcode 3. 无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串
- [Leetcode] 3.无重复字符的最长子串
- LeetCode5.python实现:最长回文子串问题☆☆
- LeetCode - 无重复字符的最长子串
- LeetCode 3. Longest Substring Without Repeating Characters--不包含重复字符的最长子串长度
- (python3)最长无重复字符子串Longest Substring Without Repeating Characters
- 求字符串的不重复字符的最长子串长度的问题
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- leetcode 395. 至少有K个重复字符的最长子串
- Leetcode:395至少有K个重复字符的最长子串(C++)
- Python简单实现查找一个字符串中最长不重复子串的方法