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 asubstring,"pwke"
is asubsequence and not a substring.
JAVA代码如下:
public class Solution {
private boolean []record;
public int lengthOfLongestSubstring(String s) {
record = new boolean[256];
int start = 0, count = 0, result = 0;
for(int i = 0; i < s.length(); i++)
{
if(!record[s.charAt(i)])
{
count++;
record[s.charAt(i)] = true;
}
else
{
result = Math.max(result, count);
while(s.charAt(start) != s.charAt(i))
{
record[s.charAt(start)] = false;
start++;
count--;
}
start++;
}
}
result = Math.max(result, count);
return result;
}
}
C++代码如下:
class Solution {
private:
bool use[256];
public:
int lengthOfLongestSubstring(string s) {
int count = 0, result = 0, start = 0;
memset(use, true, sizeof(use));
for(int i = 0; i < s.size(); i++)
{
if(use[s[i]])
{
use[s[i]] = false;
count++;
}
else
{
result = max(count, result);
while(s[start] != s[i])
{
use[s[start]] = true;
start++;
count--;
}
start++;
}
}
result = max(count, result);
return result;
}
};