题目:
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.
思路:
题目要求的是没有重复字符的最长子字符串的长度。
检查重复显然可以用 k-v mapping.所以剩下只需要考虑如何在一次迭代遍历过程中度量子串长度。
| char | pos |
|---|---|
| a | 0 |
| b | 1 |
| c | 2 |
如上图所示:将char和各自的索引值组成kv-mapping,用trace存储更新不重复的char,通过查询当前trace表就可知,是否呦重复字母出现,若pos >= start,故此刻诞生一个 substr. 长度为i-start,start更新为pos+1.
代码:
/*
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.
*/
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// 创建kv-map
unordered_map<char, size_t> trace;
// 创建重新搜索的起始索引变量
size_t start = 0;
// 记录历史最长子串长度变量
size_t rec = 0;
// 一次遍历
for (size_t i = 0; i != s.size(); i++)
{
// 搜索当前索引对应的char之前是否出现过
auto found = trace.find(s[i]);
// 如果出现过,说明该索引之前的子串为最大子串
if (found != trace.end() && found->second >= start)
{
// 计算此次的最大子串的长度
//rec = i - found->second;
// 比较此次的最大子串的长度和历史长度,记录最大值
rec = max(rec, i - start);
// 将下次搜索的起始索引重置为前面重复字母索引+1
start = found->second + 1;
}
// 更新trace
trace[s[i]] = i;
}
// 遍历完毕再做最后一次比较
rec = max(rec, s.size() - start);
return rec;
}
};
本文介绍了一种高效算法,用于查找给定字符串中最长的无重复字符子串的长度。通过使用哈希表跟踪字符及其索引,该算法能够在一次遍历中找到答案。
707

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



