3. 无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> set_char;
deque<char> deque_char;
size_t result = 0;
for(auto& c : s)
{
while(set_char.find(c) != set_char.end())
{
set_char.erase(deque_char.front());
deque_char.pop_front();
}
{
set_char.insert(c);
deque_char.push_back(c);
result = std::max(result,deque_char.size());
}
}
return result;
}
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> set_char;
int result = 0;
int temp_length = 0;
int left = 0;
for(int i = 0; i < s.size(); i++)
{
while(set_char.find(s[i]) != set_char.end())
{
set_char.erase(s[left]);
left++;
}
{
set_char.insert(s[i]);
result = std::max(result, i - left + 1);
}
}
return result;
}
};
文章提供了两种C++解决方案,分别使用unordered_set和deque来找出给定字符串中不包含重复字符的最长子串的长度。通过滑动窗口策略优化了时间复杂度。
845

被折叠的 条评论
为什么被折叠?



