求最长无重复字符字串,LeetCode Longest Substring Without Repeating Characters 这题目挺考察基本功的。如果发现重复的字符搜索起点需要回退。刚开始忘了,后来才补上。上代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ns = s.size();
int maxlen = 0,countlen = 0;
bool letterfond[256]={0};
int letterposition[256]={0};
for(int i = 0;i
{
if(letterfond[s[i]])
{
memset(letterfond,0,256*sizeof(bool));
i = letterposition[s[i]];
maxlen = max(maxlen,countlen);
countlen = 0;
//找到重复的字符后,继续查找的起始位置是上一次找到这个符号的下一个
}
else
{
countlen++;
letterfond[s[i]]=true;
letterposition[s[i]] = i;
if(i==ns-1)
maxlen = max(maxlen,countlen);
}
}
return maxlen;
}
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ns = s.size();
int maxlen = 0,countlen = 0;
bool letterfond[256]={0};
int letterposition[256]={0};
for(int i = 0;i
{
if(letterfond[s[i]])
{
memset(letterfond,0,256*sizeof(bool));
i = letterposition[s[i]];
maxlen = max(maxlen,countlen);
countlen = 0;
//找到重复的字符后,继续查找的起始位置是上一次找到这个符号的下一个
}
else
{
countlen++;
letterfond[s[i]]=true;
letterposition[s[i]] = i;
if(i==ns-1)
maxlen = max(maxlen,countlen);
}
}
return maxlen;
}
};