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.
Subscribe to see which companies asked this question.
class Solution {
public:
int lengthOfLongestSubstring(string s) { //考虑大写字符
int len = s.length();
if(len == 0)
return 0;
//pos[]存储每个字符最新出现的位置,curi和curj表示当前没有重复字符区间,posi和posj表示最长的没有重复字符的区间
int pos[200], curi, curj, posi, posj, i;
for(i = 0; i < 200; i++)
pos[i] = -1;
curi = 0;
curj = 0;
posi = 0;
posj = 0;
pos[s[0]] = 0;
for(i = 1; i< len; i++){
if(pos[s[i]] < curi){ //该字符未在当前区间出现过
curj = i;
}else if((curj - curi) > (posj - posi)){ //当前字符在当前区间出现过,且当前区间的长度大于之前的最长区间
posi = curi; //更新最长区间
posj = curj;
curi = pos[s[i]] + 1; //更新当前区间
curj = i;
}else{ //当前字符在当前区间出现过,且当前区间的长度小于之前的最长区间
curi = pos[s[i]] + 1; //更新当前区间
curj = i;
}
pos[s[i]] = i; //更新当前字符的最新位置
}
if((curj - curi) > (posj - posi)){ //跳出循环后判断当前区间是否大于之前的最长区间
posi = curi;
posj = curj;
}
return posj - posi + 1;
}
};
本文介绍了一种求解字符串中最长无重复字符子串的算法实现,通过维护字符的最新位置来高效地找到符合条件的最长子串。讨论了不同输入情况下的处理方式,并提供了完整的C++代码示例。
884

被折叠的 条评论
为什么被折叠?



