解題思路
紀錄帶只會在右端新增或刪除,所以用堆疊保存字母,另替 26 個字母保存仍在帶上的位置。加入 c 後,若位置數等於門檻,就取 c 的第一個位置作為截斷點,逐個彈出後綴,並同步彈出那些字母的位置。
每一步開始時,位置串列恰好描述帶上所有同字母位置;加入與同步刪除都維持這個不變量。因此第一個位置就是題目要求的最左 c。每個輸入字元只入棧一次、出棧至多一次,整趟刪除總量不超過 n;最大長度必須在刪除完成後才更新。
時間 O(n),帶與位置串列 O(n+26);Python 讀入字串及 split 緩衝 O(n),整體 O(n)。
Step-by-step animation
逐步教學推演:依各步描述的例子觀察狀態、轉移與答案。
步驟 1 / 3
附加首字
門檻 a=2、b=2,讀入 aba。
a
- 長度
- 1
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> q(26);
for (int &x : q)
cin >> x;
string s;
cin >> s;
vector<int> st;
vector<vector<int>> p(26);
int ans = 0;
for (char ch : s) {
int c = ch - 'a';
p[c].push_back(st.size());
st.push_back(c);
if (p[c].size() == q[c]) {
int cut = p[c][0];
while (st.size() > cut) {
p[st.back()].pop_back();
st.pop_back();
}
}
ans = max(ans, (int)st.size());
}
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。