3. Longest Substring Without Repeating Characters
3. Longest Substring Without Repeating Characters
最长不含重复字符的子字符串
int lengthOfLongestSubstring(string s) {
if (s.size() == 0) return 0;
int curLen = 0;
int maxLen = 0;
// 用来记忆上一次字符出现的位置
vector<int> pos(256, -1);
for(int i=0;i<s.size();++i) {
int prepos = pos[s[i]];
// 没出现过或者出现位置在长度范围外,继续计数
if (prepos == -1 || i - prepos > curLen) {
++curLen;
} else {
// 否则,在长度范围内,只能取新的长度值
maxLen = max(maxLen, curLen);
curLen = i-prepos;
}
// 每次都记录字符位置以便查询
pos[s[i]] = i;
}
maxLen = max(maxLen, curLen);
return maxLen;
}#DP