题目
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.
分析
题目求的是最大的不重复长度
利用一个vector,v[s[i]]是将所有相同字符的都标记为i
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> v (256, -1);
int start = -1;
int length = 0;
for (int i = 0; i < s.length(); i++)
{
if (v[s[i]]>start)
start=v[s[i]];
v[s[i]]=i;
length = max(length, i - start);
}
return length;
}
};