leetcode76 & 904
题目:水果成篮
class Solution {
public:
int totalFruit(vector<int>& fruits) {
if (fruits.size() < 3){
return fruits.size();
}
int n1 = fruits[0];
int x = 1;
while (x < fruits.size() && fruits[x] == n1){
x++;
}
if (x == fruits.size()){
return fruits.size();
}
# 对特殊情况进行单独分类讨论
int n2 = fruits[x];
int l = x + 1;
int s = 0;
int temp;
for (int i = x + 1; i < fruits.size(); i++){
if (fruits[i] != n1 && fruits[i] != n2){
s = i - 1;
while (fruits[s] == fruits[i - 1]){
s--;
}
s++;
n1 = fruits[i];
n2 = fruits[i - 1];
}
l = l > (i - s + 1) ? l : (i - s + 1);
}
return l;
}
};
class Solution {
public:
int totalFruit(vector<int>& fruits) {
int n = fruits.size();
unordered_map<int, int> cnt;
# 要学会使用STL作为工具
int left = 0, ans = 0;
for (int right = 0; right < n; ++right) {
++cnt[fruits[right]];
while (cnt.size() > 2) {
auto it = cnt.find(fruits[left]);
--it->second;
if (it->second == 0) {
cnt.erase(it);
}
++left;
}
# 采用了不同的方法寻找左边界
ans = max(ans, right - left + 1);
}
return ans;
}
};
题目:最小覆盖字串
class Solution {
public:
unordered_map<char, int> test, c;
bool compare() {
for (auto i : test) {
if (i.second > c[i.first]) {
return false;
}
}
return true;
}
#这样写可以加速程序运行
string minWindow(string s, string t) {
for (auto i : t) {
test[i]++;
}
int fs = 0;
int begin = 0;
int num = s.size() + 1;
for (int i = 0; i < s.size(); i++) {
c[s[i]]++;
while (compare() && begin <= i) {
if (i - begin + 1 < num) {
num = i - begin + 1;
fs = begin;
}
c[s[begin++]]--;
}
}
string r = (num == s.size() + 1) ? "" : s.substr(fs, num);
return r;
}
};
#滑动数组基本思想,右边界点移至满足条件后,移动左边界点
class Solution {
public:
string minWindow(string s, string t) {
vector<int> need(128, 0);
int count = 0;
for (char c : t)
{
need[c]++;
}
count = t.length();
int l = 0, r = 0, start = 0, size = INT_MAX;
while (r < s.length())
{
char c = s[r];
if (need[c] > 0)
count--;
need[c]--; //先把右边的字符加入窗口
if (count == 0) //窗口中已经包含所需的全部字符
{
while (l < r && need[s[l]] < 0) //缩减窗口
{
need[s[l++]]++;
} //此时窗口符合要求
if (r - l + 1 < size) //更新答案
{
size = r - l + 1;
start = l;
}
need[s[l]]++; //左边界右移之前需要释放need[s[l]]
l++;
count++;
}
r++;
}
return size == INT_MAX ? "" : s.substr(start, size);
}
};
#该法和最开始的的方法类似,但该法利用need[s[l]]<0可以将左侧多余的点全部清除