题目
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
解法思路
- 既然是让求没有重复元素的最大子串,于是想到用滑动窗口在给定字符串 s 中“向右滑动”的过程中,将新纳入滑动窗口的字符丢入一个集合;
- 用一个变量
lengthRecord
记录出现的无重复子串的最长长度; - 如果每次纳入滑动窗口的新字符都能成功的丢入这个集合,那么记录
lengthRecord
就会不断被打破; - 如果纳入滑动窗口的新字符无法被丢入滑动窗口,说明滑动窗口中已经存在这个字符,那么就要缩短滑动窗口到与新字符重复的字符的右边,此时记录
lengthRecord
不因滑动窗口纳入新的字符而被打破,于是继续“向右滑动”窗口,期待以后的某一时刻,当有新字符纳入滑动窗口时,会打破记录lengthRecord
;
时间复杂度
- O(N);
关键词
滑动窗口
哈希表
双指针
字符串
解法实现
- 滑动窗口的边界用变量
l
和r
表示,滑动窗口中的字符用集合windowSet
盛接;
package leetcode._3;
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int lengthOfLongestSubstring(String s) {
int l = 0, r = -1;
int lengthRecord = 0;
Set<Character> windowSet = new HashSet<>(s.length());
while (l < s.length() && r + 1 < s.length()) {
r++;
char c = s.charAt(r);
boolean isAdded = windowSet.add(c);
if (!isAdded) {
while (s.charAt(l) != c && l + 1 < s.length()) {
windowSet.remove(s.charAt(l));
l++;
}
windowSet.remove(s.charAt(l));
l++;
windowSet.add(c);
}
lengthRecord = Math.max(lengthRecord, windowSet.size());
}
return lengthRecord;
}
public static void main(String[] args) {
int result = (new Solution()).lengthOfLongestSubstring("abcabcbb");
System.out.println(result);
}
}