鏈接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
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.
(1)滑動(dòng)窗口思想
滑動(dòng)窗口為[i,j-1],如果滑動(dòng)窗口中存在字符(位置k)與j位置的字符相同,則從set集合中刪除[i,k]之間的所有字符;如果滑動(dòng)窗口中不存在字符與j位置的字符相同,則將j位置的字符加入set集合。
public int lengthOfLongestSubstring(String s) {
int n = s.length();
Set<Character> set = new HashSet<>();
int ans = 0, i = 0, j = 0;
while (i < n && j < n) {
if (!set.contains(s.charAt(j))) {
set.add(s.charAt(j++));
ans = Math.max(ans, j - i);
} else {
set.remove(s.charAt(i++));
}
}
return ans;
}
(2)優(yōu)化的滑動(dòng)窗口