C++ 实现最长无重复子串长度 | 算法详解及代码
可以使用滑动窗口的方法来解决这个问题。
首先,定义一个哈希集合来存储字符,以及两个指针 start 和 end 来表示滑动窗口的起始和结束位置。初始化 start 和 end 为 0。
然后,我们开始遍历字符串 s:
- 如果当前字符 s[end] 不在哈希集合中,说明它是一个新字符,我们将其加入哈希集合,并将 end 指针向右移动一位。
- 如果当前字符 s[end] 在哈希集合中,说明已经出现了重复字符,我们需要将 start 指针向右移动一位,并从哈希集合中移除对应的字符,直到窗口中不再包含重复字符。
在遍历的过程中,我们不断更新最长子串的长度,即 end - start。最终返回最长子串的长度即可。
下面是使用 C++ 实现的代码:
#include <unordered_set>
#include <algorithm>
int lengthOfLongestSubstring(string s) {
unordered_set<char> set;
int n = s.length();
int start = 0, end = 0;
int maxLength = 0;
while (start < n && end < n) {
if (set.find(s[end]) == set.end()) {
set.insert(s[end]);
end++;
maxLength = max(maxLength, end - start);
} else {
set.erase(s[start]);
start++;
}
}
return maxLength;
}
通过以上代码,可以得到给定字符串中不含有重复字符的最长子串的长度。
原文地址: https://www.cveoy.top/t/topic/mvw 著作权归作者所有。请勿转载和采集!