LeetCode OJ:Longest Substring Without Repeating Characters(最长无重复字符子串)

时间:2023-03-09 23:59:05
LeetCode OJ:Longest Substring Without Repeating Characters(最长无重复字符子串)

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

使用双指针,前一个指针向前走,有不相同的字符的时候标记即可,发现相同时停止,这是后面的字符向后走,直到发现这个字符,然后前指针继续向前走,一直重复直到整个过程的结束,代码如下:

 class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(!s.size()) return ;
int i = , j = ;
int maxSubLen = ;
bool canUse[]; //char类型只有256个
memset(canUse, true, sizeof(canUse));
canUse[s[]] = false;
while(j < s.size()){
if(!canUse[s[j]]){
maxSubLen = max(maxSubLen, j - i);
while(i < j){
if(s[i] != s[j])
canUse[s[i]] = true, ++i;
else{
i++;
break;
}
}
}else{
maxSubLen = max(maxSubLen, j - i + );
canUse[s[j]] = false;
}
++j;
}
return maxSubLen;
}
};

写的有点乱啊,见谅见谅。。