【LeetCode】Longest Substring Without Repeating Characters

来源:互联网 发布:mysql替换部分字符串 编辑:程序博客网 时间:2024/06/10 20:47

题目描述:

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

一开始题目理解错误,或者是受前面输出子集的影响,直接取了不重复的字母数……

最开始试了下暴力枚举,O(n*n)复杂度,不出意外TLE。

然后考虑用map<char, int>来储存之前出现过的字符位置,每当出现重复字符时,将指针移回该字符上次出现的位置,map清空重新遍历,在过大数据的时候还是TLE,不过显然走的比之前远一点。

再然后考虑怎么将其优化到O(n)。再使用一个index变量来储存重复字符上次出现的位置,判定字符重复时加一个条件,即该字符上次出现的位置在index后面,这样就避免了将指针回移进行重复遍历。

代码如下:

class Solution {public:int lengthOfLongestSubstring(string s) {int count(0), index(0), res(0);unordered_map<char, int> dup;for (int i = 0; i < s.length(); i++){if (dup.count(s[i])&&dup[s[i]]>=index){index = dup[s[i]];count = i - index - 1;}dup[s[i]] = i;count++;res = std::max(res, count);}return res;}};


0 0
原创粉丝点击