力扣刷題:3. 無重複字元的最長子串
阿新 • • 發佈:2021-01-30
題目要求
給定一個字串,請你找出其中不含有重複字元的最長子串的長度。
提示
我的程式碼
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> set;
unsigned lenth = s.size();
int left = 0, right = 0, maxLenth = 0;
while (left < lenth)
{
while (right < lenth && set.count(s[right]) == 0)
{
set.insert(s[right++]);
}
maxLenth = std::max(maxLenth, right - left);
set.erase(s[left++]);
}
return maxLenth;
}
};
學到的東西
1、滑動視窗的運用:left和right的區間限定了分析子串。通過控制left,使得該子串不侷限於“起點要從最左邊開始”。通過依次移動right,使得最終能夠分析完整個字串。
2、無序容器set的運用:此題set儲存了分析子串所具有的字元。並且通過set的count函式來判斷新的字元是否已經存在於已經儲存的分析子串中。
3、leetcode的c++環境:
using namespace std;
自動包含所需的容器標頭檔案
目前看來什麼都能用?