class Solution {
//put last char in the end of the string
//to avoid extra judge, when go to the end without repeating char
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(s.size() == 0) return 0;
//put last char in the end of the string
//to avoid extra judge, when go to the end without repeating char
s.push_back(s[s.size()-1]);
vector<bool> cntT(256, false);
int maxLen = 0;
int left = 0;
for (int i = 0; i < s.size(); ++i)
{
if(cntT[s[i]] == true)
{
if (i-left > maxLen)
maxLen = i-left;
while (s[left] != s[i])
cntT[s[left++]] = false;
cntT[s[left++]] = false;
}
cntT[s[i]] = true;
}
return maxLen;
}
};
second time
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<bool> charTable(256, false);
int maxLen = 0;
int startIndex = 0;
int i;
for(i = 0; i < s.size(); ++i)
{
if(charTable[s[i]] == true)
{
maxLen = max(i-startIndex, maxLen);
while(s[startIndex] != s[i])
charTable[s[startIndex++]] = false;
startIndex++;
}
else charTable[s[i]] = true;
}
return max(maxLen, i-startIndex);
}
};
本文介绍了一种用于寻找字符串中最长无重复字符子串的算法实现。通过使用布尔型向量记录字符出现状态,并迭代检查每个字符,一旦发现重复字符即更新最大长度并移动起始位置,从而高效解决问题。
714

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



