已知一个字符串,求用该字符串的无重复字符的最长子串的长度。例如:
s=“abcabcbb”->“abc”,3
s=“bbbbb”->“b”,1
s=“pwwkew”->“wke”,3
注意"pwke"是子序列而非子串。
#include<string>
class Solution
{
public:
Solution() {}
~Solution() {}
int longestOfSubString(std::string s)
{
int result = 0;
int begin = 0;
int char_map[128] = { 0 };
std::string word = "";
for (int i = 0; i < s.length(); i++)
{
char_map[s[i]]++;
if (char_map[s[i]]==1)
{
word += s[i];
if (result<word.length())
{
result = word.length();
}
}
else
{
while (begin<i&&char_map[s[i]]>1)
{
char_map[s[begin]]--;
begin++;
}
word = "";
for (int j = begin; j <=i; j++)
{
word += s[j];
}
}
}
return result;
}
};
int main()
{
std::string s = "abcbadab";
Solution solve;
printf("%d\n", solve.longestOfSubString(s));
return 0;
}
运行结果为:
4