【leetcode每日一题】【2019-04-10】3.无重复字符的最长子串
2019-04-10 15:19
337 查看
3.无重复字符的最长子串
地址: https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/submissions/
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 示例 3: 输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
解题思路:
暴力解决
遍历所有的情况,然后一个个看是否有重复,长度是多少
代码如下:
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len=0 for i in range(len(s)): tmp_str=[] for j in (range(i,len(s))): if s[j] not in tmp_str: tmp_str.append(s[j]) else: break if len(tmp_str)>max_len: max_len=len(tmp_str) return max_len
提交代码后,发现最后一次测试用例没有通过。 测试用例里面字符串有3w多个字符。
看了下解题思路
方法三:优化的滑动窗口
上述的方法最多需要执行 2n 个步骤。事实上,它可以被进一步优化为仅需要 n 个步骤。我们可以定义字符到索引的映射,而不是使用集合来判断一个字符是否存在。 当我们找到重复的字符时,我们可以立即跳过该窗口。
也就是说,如果 s[j]s[j] 在 [i, j)[i,j) 范围内有与 j’j
′
重复的字符,我们不需要逐渐增加 ii 。 我们可以直接跳过 [i,j’][i,j
′
] 范围内的所有元素,并将 ii 变为 j’ + 1j
′
+1。
优化后的代码:
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: i=0 tmp_str="" max_len=0 for j in range(len(s)): if tmp_str.count(s[j])>0: i=tmp_str.find(s[j])+1 tmp_str=tmp_str[i:]+s[j] else: tmp_str=tmp_str+s[j] max_len=max(max_len,len(tmp_str)) return max_len
Scala代码
object Solution { def lengthOfLongestSubstring(s: String): Int = { var i=0 var tmp_str="" var max_len=0 for ( j <- 0 to s.length-1 ){ if (tmp_str.indexOf(s(j))>=0){ i=tmp_str.indexOf(s(j))+1 tmp_str=tmp_str.substring(i).concat(s(j).toString()) }else{ tmp_str=tmp_str.concat(s(j).toString()) } max_len=math.max(max_len,tmp_str.length) } return max_len } }
相关文章推荐
- 每日一算-3. 无重复字符的最长子串
- Leetcode 3.无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串(Java 版)
- [Leetcode] 3.无重复字符的最长子串
- LeetCode题目C++实现:3. 无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(Java)
- LeetCode 3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- Leetcode(C++)——3. 无重复字符的最长子串
- Leetcode刷题35-3.无重复字符的最长子串(C++)
- 【leetcode】3. 无重复字符的最长子串
- 【Leetcode】3. 无重复字符的最长子串[未解出]
- LeetCode题解(python)-3.无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- LeetCode-3.无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- 【Leetcode一刷】3.无重复字符的最长子串
- Leetcode每日一道 -- 无重复字符的最长子串