用i表示左边界,dic字典中的元素为数字最后一次出现的索引 当遇到重复元素,更新左边界,更新最后一次出现的索引
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> dic;
int i = -1, res = 0, len = s.size();
for (int j = 0; j < len; ++j) {
if (dic.count(s[j]))
i = max(i, dic[s[j]]);
dic[s[j]] = j;
res = max(res, j - i);
}
return res;
}
};
删掉一个元素之后全为1的最长子数组,转化为只包含一个0的最长子数组,跟前一题一样,i表示左边界,用zidx表示0最后一次出现的索引,当重复碰到0时,更新zidx和左边界。得到最长长度之后,把包含的那个0去掉,就是答案。
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int i = -1, res = 0, n = nums.size(), zidx = -1;
for (int j = 0; j < n; ++j) {
if (nums[j] == 0) {
if (zidx >= 0) i = max(i, zidx);
zidx = j;
}
res = max(res, j - i);
}
return res - 1;
}
};