LeetCode-3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
思路:本题要求求解最大子序列(无重复字母)的长度,可以利用unordered_map存储字母来检查是否出现重复。用start来标记有效序列的起点,用ret来表示序列的最大子序列的长度。注意更新序列有效起点的表示为
start = found->second+1 ;另外还要注意出现“abba”这种情况,该情况会改变有效起点,因为当查找到第二个a时,起点不能变为第一个b,而应该直接将a加入,继续向后读,因此加上条件
found->second >= startclass Solution {
public:
int lengthOfLongestSubstring(string s)
{
unordered_map<char, size_t> trace;
size_t ret = 0, start = 0;
for (size_t i = 0; i < s.size(); i++)
{
auto found = trace.find(s[i]);
if (found != trace.end() && found->second >= start)
{
ret = max(ret, i -start);
start = found->second+1 ;
}
trace[s[i]] = i;
}
return max(ret, s.size() - start);
}
};

本文提供LeetCode第3题的解决方案,通过使用unordered_map跟踪字符出现的位置,实现寻找最长不含重复字符的子字符串。文章详细解释了算法逻辑,并附带完整的C++代码实现。
717

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



