目录
1,题目描述
英文描述
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:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2,解题思路
采用滑动窗口的思想,利用左右指针限定窗口范围,保证窗口内字符均不重复:
- 在一次循环中,左指针left每次右移一位,右指针right则一直右移,直到出现重复元素为止;
- 更新窗口尺寸(不含重复字符的子串长度);
小技巧:
- 集合unordered_set包含在头文件<unordered_set>中;
- 对集合record的操作
- 插入:record.insert(相应类型的元素);
- 删除指定值的元素:record.erase(指定元素的值);
- 判断集合中是否已存在元素:record.count(想要查找的元素)<1,即不存在;
3,AC代码(C++)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> record; //存放区间所有字符
int n = s.length(), right = 0, ans = 0; //right指向重复的第一个字符位置
for(int i = 0; i < n; i++){ //左指针i自动向右移
if(i != 0){
record.erase(s[i - 1]); //将左指针所指数据移除
}
while(right < n && record.count(s[right]) < 1){ //每次右指针定位第一个区间内重复的元素位置
record.insert(s[right++]);
}
ans = max(ans, right - i); //由于右指针指向s第一个重复位置 这里求a区间长度不需要减一1
}
return ans;
}
};