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 {
public:
int lengthOfLongestSubstring(string s) {
}
};
如题所示:要求找出不含有重复字母的最长字串。
解决方法:建立两个下标i和j,分别对应当前子串的起始位置和终点位置,j从0开始向右移动。
在检索过所有的字符,即j=s.length()的时候,停止扫描。
此外,需要设置一个256大小的数组exist用于存储出现在当前子串的字符。
流程如下:
1.判断当前字符s[j]是否已经出现在当前子串中。
2.若不出现在当前子串中,则将该字符对应的在exit数组中的ASCII码下标设置为true,并将j向右移动一个单位,最大长度maxLen加1。
3.若出现在当前子串中,则需要将起始位置i移至该字符第一次出现的位置处,并将之前的字符在exit数组中的对应位置设为false,由于需要寻找新的子串,所以需要将i和j都向右移动一个单位。最后再比较maxLen和当前子串长度j-i的大小,并将maxLen更新为其中较大者。
代码实现如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i=0,j=0;
int maxLen = 0;
bool exist[256]={false};
while(j<s.length()){
if(!exist[s[j]]){
exist[s[j]]=true;
j++;
}else{
while(s[i]!=s[j]){
exist[s[i]]=false;
i++;
}
i++;
j++;
}
maxLen = maxLen > j-i ? maxLen:j-i;
}
return maxLen;
}
};