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.
Personal Tips: 使用map。但是看LeetCode上面参考可以使用另一个数组。代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty()) return 0;
int pos = 0, left = 0, right = 0, length = 0, max = 1;map<char, int> num;
while (right <= s.size())
{
if (num.count(s[right]))
{
if (num[s[right]] >= left)
{
length = right - left;
if (max < length)
{
max = length;
pos = left;
}
left = (num[s[right]] + 1);
num[s[right]] = right;
++right;
continue;
}
else
{
num[s[right]] = right;
++right;
continue;
}
}
else if (right >= (s.size() - 1))
{
length = s.size() - left;
if (max < length)
{
max = length;
pos = left;
}
break;
}
num.insert(pair<char, int>(s[right], right));
++right;
}
return max;
}
};