150. 括号画家
题意:
求长度最长的合法括号子串
思路:
经典的dp解法
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 1e6 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
int f[maxn];// f[i] 表示以 i 结尾的合法子串长度
string s;
void work()
{
cin >> s; n = s.size();
s = "@" + s;
int ans = 0;
for(int i = 1; i <= n; ++i){
int j = i - 1 - f[i-1];
if(s[i] == '(' || s[i] == '{' || s[i] == '[') continue;
if(s[i] == ')' && s[j] == '(' || s[i] == ']' && s[j] == '[' || s[i] == '}' && s[j] == '{')
f[i] = f[i-1] + (j - 1 >= 1 ? f[j-1] : 0) + 2;
ans = max(ans, f[i]);
}
cout << ans;
}
int main()
{
ios::sync_with_stdio(0);
// int TT;cin>>TT;while(TT--)
work();
return 0;
}
4207. 最长合法括号子序列
子序列贪心即可
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 2e5 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
void work()
{
string s;cin >> s;
stack<bool> st;
int ans = 0;
for(auto x : s)
{
if(x == '(') st.push(1);
else
{
if(st.size()) st.pop(), ans += 2;
}
}
cout << ans;
}
int main()
{
ios::sync_with_stdio(0);
// int TT;cin>>TT;while(TT--)
work();
return 0;
}