题目描述
Given a string, find the length of the longest substring without repeating characters.
- For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3.
- For “bbbbb” the longest substring is “b”, with the length of 1.
解题思路
如下图所示:左侧为遍历字符串操作,当遇到重复的字符串时,得到的新的substring为重复字符串后面部分的字符串与被遍历到的字符串相连部分。例如当”abc”遍历到第四号位的’a’时,原substring中的”bc”被保留,并与新的字符串相连。
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() == 1 || !s.size())
return s.size();
string sub;
int max = 0;
for (size_t i = 0; i != s.size(); ++i)
{
char c = s[i];
if (sub.find(c) != string::npos)
{
max = max > sub.size() ? max : sub.size();
int idx = sub.find(c);
sub = sub.substr(idx + 1);
}
sub.append(1, c);
}
max = max > sub.size() ? max : sub.size();
return max;
}
};