leetcode03.无重复字符的最长子串

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。


示例:

1
2
3
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。


分析:

1
滑动窗口经典问题,使用哈希表维护一个窗口,当右指针对应字符大于1时,收缩窗口

代码

  • C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> cnt;
int res = 0;
for (int i = 0, j = 0;i < s.size();i ++) {
cnt[s[i]] ++;
while (cnt[s[i]] > 1) -- cnt[s[j ++]];
res = max(i - j + 1, res);
}

return res;
}
};

[原题链接](3. 无重复字符的最长子串 - 力扣(Leetcode))

0%