Problem
\3. Longest Substring Without Repeating Characters
Medium
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
First Submit AC
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int Sum = 0, thisSum = 0, length = s.size();
string Tmp;
size_t Pos;
//queue<char> V;
for (size_t i = 0; i < length; i++)
{
if (Tmp.find(s[i]) == string::npos)
{
Tmp += s[i];
thisSum = Tmp.size();
if (thisSum > Sum)
{
Sum = thisSum;
}
}
else
{
Pos = Tmp.find(s[i]);
Tmp.erase(0, Pos + 1);
Tmp += s[i];
}
}
return Sum;
}
};
算法时间复杂度:O(N2) 空间复杂度:O(N);
- 类比O(N)的maximum subsequence的算法,有该字符则进入字符串,得到sum,无则找到截断的位置,然后再进入字符串
Online Way
- 大胆用max函数简化代码
- slide window, 取位置[i, j) 为没有重复字符的字符串,然后对位置j进行操作,通过重复与否,i可以渐变或者跳变,取sum = max(sum , i - j + 1);
Improve Field
算法能力太弱了!
Reduced Code
#include<unordered_map>
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int Sum = 0, length = s.size();
unordered_map<char, int> MyMap;
int begin = 0;
for (int i = 0; i < length; i++)
{
if (MyMap.find(s[i]) != MyMap.end())
{
begin = max(begin, MyMap[s[i]]);
}
Sum = max(Sum, i - begin + 1 );
MyMap[s[i]] = i + 1;
}
return Sum;
}
};