
解题思路
滑动窗口+哈希表
用unordered_map<char, int>temp_s记录单个字符和下标,记录每一次开始的下标left;
如果第i个字符不在哈希表中,就把这一个字符加进去,如果第i个字符在哈希表中,则left从i+1开始,子串长度为i-left+1
注:
找到的某一个字符不仅要在哈希表中,而且要在left和i之间才算,所以这里限制
if (it != temp_s.end()&&it->second>=left)
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 0)
return 0;
unordered_map<char, int>temp_s;
int left = 0;
int result = 1;
for (int i = 0; i < s.size(); i++)
{
auto it = temp_s.find(s[i]);
if (it != temp_s.end()&&it->second>=left)left = temp_s[s[i]] + 1;
temp_s[s[i]] = i;
result = max(result, i - left + 1);
}
return result;
}
};
本文介绍了如何利用滑动窗口和哈希表解决字符串中最长无重复子串的问题。通过维护一个哈希表记录字符及其下标,不断更新窗口边界并计算最长子串长度。这种方法有效地避免了回溯,提高了算法效率。
868

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



