LeetCode 3. 无重复字符的最长子串
2020-03-26 07:23
225 查看
3. 无重复字符的最长子串 解题思路
题目:
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
思路:
利用HashSet无法存储相同元素,采用滑动窗口来解题。每次把字符add进集合时判断是否包含该元素,如果包含就把当前窗口最前端的元素移除,窗口左端右移一;不包含则把元素加入集合,窗口右端右移一,并判断当前窗口长度是否大于之前的窗口长度。
代码:
class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0, i = 0, j = 0; Set<Character> set = new HashSet<>(); while (i < n && j < n) { if (!set.contains(s.charAt(j))){ set.add(s.charAt(j)); j++; ans = Math.max(ans, j - i); } else { set.remove(s.charAt(i++)); } } return ans; } }
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- Leetcode3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串 Python
- LeetCode 3. 无重复字符的最长子串
- Leetcode(C++)——3. 无重复字符的最长子串
- [Leetcode] 3.无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(Java)
- 【leetcode】3. 无重复字符的最长子串
- LeetCode--3.无重复字符的最长子串
- 【LeetCode】3. 无重复字符的最长子串(Longest Substring Without Repeating Characters,24.2%,中等)
- LeetCode 3. 无重复字符的最长子串
- LeetCode题目C++实现:3. 无重复字符的最长子串
- leetcode3. 无重复字符的最长子串
- Leetcode——3.无重复字符的最长子串
- 【leetcode每日一题】【2019-04-10】3.无重复字符的最长子串
- leetcode 3.无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串
- Leetcode刷题35-3.无重复字符的最长子串(C++)
- 【Leetcode】3. 无重复字符的最长子串[未解出]
- LeetCode 3. 无重复字符的最长子串
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)