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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int>fre(255,0);
int curLen = 0;
int maxLen = 0;
int length = s.length();
int start = 0;
for(int i = 0; i< length; i++)
{
char ch = s.at(i);
if(fre[ch] == 0)
{
fre[ch] ++;
curLen = i - start + 1;
if(curLen > maxLen)
maxLen = curLen;
}
else
{
if(curLen>maxLen)
maxLen = curLen;
char temp = s.at(start);
while(start < i && temp != ch)
{
fre[ temp ] = 0;
start++;
temp = s.at(start);
}
start++;
}
}
return maxLen;
}
};

本文介绍了一种算法,用于在给定字符串中找到最长的无重复字符子串。通过使用滑动窗口技巧和哈希表,实现了一个高效的解决方案。实例包括分析字符串 'abcabcbb' 和 'bbbbb' 的最长无重复子串。
466

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



