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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int result=0;
int left=0;
unordered_set<char>window;
for(int right=0;right<s.length();right++){
char c=s[right];
while(window.count(c)){
window.erase(s[left++]);
}
window.insert(c);
result=max(result,right-left+1);
}
return result;
}
};
注意:
1.同样的,left表示起始位置,right表示终止位置,均从零开始,用result来记录最后的最小长度。
2.创建一个哈希表Window,用来记录不重复的字符串
3.注意while循环,当Window里面已经有过c的时候,一直将Window的left++的元素删除,注意,left同时也会++,以此来保证最后得到的字符串长度是最小的。
4.result是result和right-left+1两者中的较大值
标签:right,int,Substring,length,Without,result,answer,Repeating,left From: https://blog.csdn.net/2301_80161204/article/details/139718239