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.
解法:
class Solution {
private:
bool canUse[256];
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
memset(canUse, true, sizeof(canUse));
int count = 0;
int ret = 0;
for(int i = 0, j = 0; i < s.size(), j < s.size(); j++)
{
if (canUse[s[j]])
{
canUse[s[j]] = false;
count++;
}
else
{
ret = max(ret, count);
while (true) {
if(s[i] == s[j]) {
canUse[s[i]] = false;
i ++;
break;
} else {
canUse[s[i]] = true;
i ++;
}
}
count = j -i + 1;
}
}
ret = max(ret, count);
return ret;
}
};