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) {
map<char, int> pos;
int maxLen = 0;
int start = 0;
int len = 0;
for(int i=0;i<s.length();++i){
char c = s[i];
if(pos.find(c)==pos.end() || pos[c] < start){
pos[c] = i;
len++;
if(maxLen < len){
maxLen = len;
}
}else{
int prePos = pos[c];
pos[c] = i; //update recent position
start = prePos + 1;
len = i - start + 1;
}
}
return maxLen;
}
};
本文介绍了一种算法,用于找出给定字符串中最长的不包含重复字符的子串长度。通过使用哈希表(map)来跟踪字符的最新位置,并随着遍历更新起始点和最大长度,实现高效求解。
958

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



