题目描述:
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.
Example 4:
Input: s = ""
Output: 0
解题思路:
题目的要求是找到字符串中最长的子串,子串的含义就是相连的字符。这里我们采用类似双指针的解法,首先使用map字符第一次出现的位置,定义l,r为两个左右指针,r负责向前遍历元素,当有map中有重复值出现时,r表示右边界,l通过处理获取左边界,区间[l,r]就是区间的长度。
代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int N = s.size();
unordered_map<char,int> pos; // 记录字符串位置
int r = 0, l = 0, res = 0;
for(; r < N; r++){
if(pos.count(s[r])) {
l = max(l,pos[s[r]]+1); // 判断窗口内是否有重复的字符串存在
}
pos[s[r]] = r;
res = max(res,r-l+1);
}
return res;
}
};
在获取左边界时要考虑一个问题,就是在这个[l,r]的区间是否还有重复的字符存在,这里就需要获取最大的l,使得[l,r]区间中不存在重复的字符,这个可以参考例子:s = abba,折中情况。