/*
* @lc app=leetcode.cn id=3 lang=cpp
*
* [3] 无重复字符的最长子串
*/
// @lc code=start
class Solution {
/*
滑动窗口算法
将字符串顺着往里面推,遇到重复就把前面的给弹出
记得保存最长长度即可
*/
public:
deque<char> q;
int res = 0;
int lengthOfLongestSubstring(string s) {
if (!s.size()) return 0;
for (int i=0; i<s.size(); ++i) {
if (q.empty() || !find(q, s[i])) {
q.push_back(s[i]);
res = res > q.size() ? res : q.size();
} else {
while (find(q, s[i]) && q.size()>0) {
q.pop_front();
}
q.push_back(s[i]);
}
}
return res;
}
bool find(deque<char>& q, char ch) {
for (int i=0; i<q.size(); ++i) {
if (q[i] == ch) {
return true;
}
}
return false;
}
};
// @lc code=end
leetcode 3.无重复字符的最长字串
最新推荐文章于 2024-05-20 18:16:07 发布