一、题目
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
二、 思路
和之前一样的思路,找那四个,或者说五个debug的点
二、自己写的
1.代码
第一次写
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> need = new HashMap<Character,Integer>();
HashMap<Character,Integer> window = new HashMap<Character,Integer>();
int right = 0, left = 0;
int valid = 0;
int start = 0, len = 0;
//need里面存的是s里面所有不重复字符,数量都是1
for (char c : s.toCharArray()) {
need.put(c, need.getOrDefault(c, 1));
}
//窗口右移
while (right < s.length()) {
char c = s.charAt(right);
right++;
//window和valid“变大”
if (need.containsKey(c)) {
//window里面放的就是窗口里面字符真实的数量
window.put(c, window.getOrDefault(c, 0) + 1);
if (need.get(c).equals(window.get(c))) {
valid++;
//改变结果
if (len < right - left)
len = right - left;
}
}
//窗口左移
while (window.get(c) > need.get(c)) {
char d = s.charAt(left);
left++;
if (need.containsKey(d)) {
if (need.get(d).equals(window.get(d)))
valid--;
window.put(d, window.get(d) - 1);
}
}
}
return len;
}
}
//正确,但是套了模板后稍微有点儿冗余,有的参数没用到。
第二次写
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> need = new HashMap<Character,Integer>();
HashMap<Character,Integer> window = new HashMap<Character,Integer>();
int left = 0, right = 0;
int valid = 0;
int start = 0, len = 0;
for (char c : s.toCharArray()) {
need.put(c, need.getOrDefault(c, 1));
}
while (right < s.length()) {
char c = s.charAt(right);
right++;
if (need.containsKey(c)) {
window.put(c, window.getOrDefault(c, 0) + 1);
if ((need.get(c).equals(window.get(c))) && (len < right - left))
len = right - left;
}
while (window.get(c) > need.get(c)) {
char d = s.charAt(left);
left++;
if (need.containsKey(d))
window.put(d, window.get(d) - 1);
}
}
return len;
}
}
//正确,很精简
三、标准答案
1.方法一(滑动窗口)
class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character,Integer> need = new HashMap<Character,Integer>();
HashMap<Character,Integer> window = new HashMap<Character,Integer>();
int left = 0, right = 0;
int valid = 0;
int start = 0, len = 0;
for (char c : s.toCharArray()) {
need.put(c, need.getOrDefault(c, 1));
}
while (right < s.length()) {
char c = s.charAt(right);
right++;
if (need.containsKey(c)) {
window.put(c, window.getOrDefault(c, 0) + 1);
if ((need.get(c).equals(window.get(c))) && (len < right - left))
len = right - left;
}
while (window.get(c) > need.get(c)) {
char d = s.charAt(left);
left++;
if (need.containsKey(d))
window.put(d, window.get(d) - 1);
}
}
return len;
}
}
2.总结
一次就过了,我太刁啦!