题目
运行结果
我的解答
#include<iostream>
#include<unordered_map>
using namespace std;
struct SectInfo
{
int startIndex;
int endIndex;
int Size() {
return endIndex - startIndex + 1;
}
SectInfo(int index, string& src):src(src),startIndex(index),endIndex(index)
{
charMap.insert(pair<char, int>(src[index], index));
}
bool AdaptNext()
{
auto newEnd = endIndex + 1;
if (newEnd == src.length())
return false;
auto newChar = src[newEnd];
if (ContainsChar(newChar))
{
auto existPos = charMap.at(newChar);
for (auto i = startIndex; i < existPos; i++)
{
charMap.erase(src[i]);
}
startIndex = existPos+1;
}
else
{
charMap.insert(pair<char, int>(newChar, -1));
}
charMap.at(newChar) = newEnd;
endIndex = newEnd;
return true;
}
bool ContainsChar(char ch)
{
return charMap.count(ch);
}
private:
const string& src;
unordered_map<char, int> charMap;
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.length() == 0)
return 0;
SectInfo sect(0, s);
int startIndex = 0, endIndex = 0, maxSize = 0;
while(true)
{
if (sect.Size() > maxSize)
{
startIndex = sect.startIndex;
endIndex = sect.endIndex;
maxSize = sect.Size();
}
if (!sect.AdaptNext())
{
break;
}
}
auto ans = s.substr(startIndex, maxSize);
return maxSize;
}
};
int main()
{
string s;
Solution solution;
while (true)
{
cin >> s;
cout<<solution.lengthOfLongestSubstring(s)<<endl;
}
}