Given a string s, please find the length of the longest substring that does not contain repeated characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: Since the longest substring without repeating characters is "abc", its length is 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: Since the longest substring without repeating characters is "b", its length is 1.
The method I adopt for this question is to use an unordered set to store the current substring, and use the unordered set to find the current element every time a new character is added, and maintain the current length and the maximum length in real time.
code first
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int left = 0,right = 0;//设定当前字串的左右边界
int curlenght = 0,maxlenght = 0;//当前子串长度和最大子串长度
unordered_set<char> set;//创建无序集来存储当前字符串
for(;right < s.size(); right++)
{
while(set.find(s[right])!=set.end())//寻找到重复字符就从当前子串最左端开始移除
{
set.erase(s[left]);
left++;
curlenght--;//将左端右移并且将当前字串--
}
set.insert(s[right]);
curlenght++;
maxlenght = max(maxlenght,curlenght);//维护最大字串长度
}
return maxlenght;
}
};
Let's take abcabcbb as an example to see the running process of the code
In the beginning, our situation was like this, and then the right kept moving to the right, putting the characters into the set until we encountered characters that were repeated with the set
When we encounter duplicate characters, move the left pointer and delete the leftmost element in the set
Just like this, then right continues to move to the right, and when it encounters duplicates, delete the leftmost element in the set until there are no duplicates
The newly added b needs to remove two elements before it can be put into the string, as shown in the figure below
In this way, we have traversed the entire tree