P1944 最长括号匹配

链接:https://www.luogu.com.cn/problem/P1944
题目:

思路:注意题目里说的:
1.(),[]是括号匹配的字符串。

2.若A是括号匹配的串,则(A),[A]是括号匹配的字符串。

3.若A,B是括号匹配的字符串,则AB也是括号匹配的字符串。
所以设dp[i]是以i结尾的最长匹配字符串的长度,那么更新状态方程可以写为:
如果s[i] == ']' and s[i-1-f[i-1]] == '['对应法则二(同理换成小括号也可以)
那么dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] - 2],就是dp[i]结尾的最长长度是两个夹起来的长度+2再加上前一个部分的最长长度(s[i-2-f[i-1]]为结尾的最长长度)
代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<sstream>
#include<string>
#include<string.h>
#include<iomanip>
#include<stdlib.h>
#include<map>
#include<queue>
#include<limits.h>
#include<climits>
#include<fstream>
#include<stack>
typedef long long ll;
using namespace std;
const int N = 1e6 +10;
ll dp[N];
int main()
{
	ll n; string s; cin >> s;
	n = s.length(); s = "0" + s;
	ll ans = 0, anslength = 0;
	for (ll i = 1; i < n; i++)
	{
		if (s[i] == ']' and s[i - 1 - dp[i - 1]] == '[')
			dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] - 2];
		else if (s[i] == ')' and s[i - 1 - dp[i - 1]] == '(')
			dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] - 2];
		if (dp[i] > anslength)
		{
			anslength = dp[i];
			ans = i;
		}
	}
	for (int i = ans - anslength + 1; i <= ans; i++)cout << s[i];
	return 0;
}

posted on 2024-05-26 11:28  WHUStar  阅读(1)  评论(0编辑  收藏  举报