LeetCode无重复字符的最大字串
题目描述
无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
题解:使用滑动窗口
使用set维护一个窗口(查找数据快),每次出现重复数据时,窗口向右移动直到该数据能插入,
每次插入数据时更新滑动窗口的maxsize
int lengthOfLongestSubstring(string s) {
if (s.empty())
return 0;
std::set<char> wind;
int index=0;
int maxsize = 0;
for (char c : s) {
//cout << c << "c" << endl;
if (wind.count(c)>0) {
// cout << 1 << "c" << endl;
while (wind.count(c) > 0) {
//cout << 2 << "c" << endl;
wind.erase(s.at(index));
index++;
continue;
}
}
wind.insert(c);
maxsize = wind.size() > maxsize ? wind.size() : maxsize;
}
return maxsize;
}