输入:s = "abcdecb"
输出:5
题意:从字符串s中找出最长的、没有重复字符的子串,返回该子串的长度。
1、暴力法
2、滑动窗口
所写方法比官法答案要快一点点。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int max = 0;
vector<char> vec;// 用vec作为滑动窗口
for(char i : s){
auto pos = find(vec.begin(), vec.end(), i);
// 如果在vec中没找到相同字符
if(pos == vec.end()){
vec.push_back(i);// 把字符存入vec
max = max < vec.size() ? vec.size() : max;// 记下vec的最长长度
// 如果在vec中找到了相同字符
}else{
vec.erase(vec.begin(), ++pos);// 删除从vec开头到相同字符的地方
vec.push_back(i);// 把字符存入vec
}
}
return max;
}
};