剑指 Offer 48. 最长不含重复字符的子字符串https://leetcode.cn/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/
dp
注意:缩小 不含重复字符子串 时的写法
dp_1 = min(i - charToIndex[s[i]], dp_0 + 1);
int lengthOfLongestSubstring(string s) {
int n = s.size();
// base case
if (n < 2)
{
return n;
}
unordered_map<char, int> charToIndex;
int dp_0 = 1;
int dp_1 = 1;
charToIndex.insert({ s[0],0 });
int res = 1;
for (int i = 1; i < n; ++i)
{
if (charToIndex.count(s[i]))
{
dp_1 = min(i - charToIndex[s[i]], dp_0 + 1);
charToIndex[s[i]] = i;
}
else
{
dp_1 = dp_0 + 1;
charToIndex.insert({ s[i],i });
}
dp_0 = dp_1;
res = max(res, dp_1);
}
return res;
}