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 len = s.size();
int i = 0, j = 1;
int res = 0;
int cnt[256] = {0};
if (len == 0) return 0;
cnt[s[i]] ++;
res = 1;
while (i < j && j < len) {
if (cnt[s[j]] == 0) cnt[s[j++]]++;
else {
if (j - i > res) res = j - i;
while (cnt[s[j]] > 0) cnt[s[i++]]--;
cnt[s[j++]]++;
}
}
if (j == len && j - i > res) res = j - i;
return res;
}
};

本文介绍了一种求解字符串中最长无重复字符子串长度的高效算法实现。通过使用滑动窗口方法并配合字符计数数组,该算法能够在O(n)的时间复杂度内找到答案。
446

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



