题目:
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.
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0;
bool used[256] = { false };
int count = 0;
int head = 0;
for (int i = 0; i < s.size(); i++) {
if (!used[s[i]]) {
used[s[i]] = true;
count++;
}
else {
ans = max(ans, count);
while (1) {
used[s[head]] = false;
count--;
if (s[head] == s[i])
break;
head++;
}
head++;
used[s[i]] = true;
count++;
}
}
ans = max(ans, count);
return ans;
}
};
本文介绍了一种解决最长无重复字符子串问题的方法。通过使用C++实现的类Solution,该方法能够在给定字符串中找到最长的无重复字符子串,并返回其长度。例如,对于输入abcabcbb,最长无重复字符子串为abc,长度为3。
696

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



