题目: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.
解题代码如下:
// 时间复杂度 O(n), 空间复杂度 O(1)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.size() <= 1) return s.size();
int max_len = 0; // 不含重复字符的最长字串长度
int start = 0; // 不含重复字符的字串的开始处
for (int i = 1; i < s.size(); ++i ) {
// 判断 s[i] 是否在不重复字串 [start, i)中出现过
for (int j = start; j < i; ++j)
if (s[i] == s[j])
break;
if (j == i) // 如果未出现
max_len = max(max_len, i - start + 1);
else { // 如过出现了
max_len = max(max_len, i - start);
start = j + 1; // 下一个不重复字串的开始处
}
}
return max_len;
}
};