题干
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.
题解1
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int len = s.size();
unordered_set<char> sub;
int maxlen = 0, i = 0, j = 0;
while(i < len && j < len)
{
if(sub.find(s[i]) == sub.end())
{
sub.insert(s[i++]);
maxlen = max(maxlen, i - j);
}
else
{
sub.erase(s[j++]);
}
}
return maxlen;
}
};
题解2 92.07%
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int len = s.size();
int maxlen = 0;
vector<int> index(128, 0);
for(int i=0, j=0; i < len; i++)
{
j = max(index[s[i]], j);
maxlen = max(maxlen, i - j + 1);
index[s[i]] = i + 1;
}
return maxlen;
}
};