zzuoj 10456: 最长匹配子串 【思维】

来源:互联网 发布:高一历史优化设计答案 编辑:程序博客网 时间:2024/04/28 23:30

题目链接:zzuoj 10456: 最长匹配子串

10456: 最长匹配子串
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 118 Solved: 22
[Submit][Status][Web Board]
Description

定义一个满足括号匹配的字符串为完美串。一个由’(‘,’)’组成的字符串,怎么才能求出
来字符串S中最长的完美串(S的子串)的长度呢?

Input

输入的第一行是一个数字k,代表输入的样例组数(k < 100)。
每组样例是一个字符串只由’(‘,’)’这两个字符组成的字符串s(|s| < 100000)。

Output

输出s中最长的匹配子串的长度。

Sample Input
3
()()
((())
(
Sample Output
4
4
0

思路:先标记出可匹配括号,然后查找连续被标记的最大段。

#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>#include <queue>#include <cmath>#include <stack>#define fi first#define se second#define ll o<<1#define rr o<<1|1#define CLR(a, b) memset(a, (b), sizeof(a))using namespace std;typedef long long LL;typedef pair<int, int> pii;const int MOD = 1e9 + 7;const int MAXN = 1e5 + 10;void add(LL &x, LL y) { x += y; x %= MOD; }char str[MAXN];bool vis[MAXN];int main(){    int t; scanf("%d", &t);    while(t--) {        scanf("%s", str); stack<int> S;        int len = strlen(str);        for(int i = 0; i < len; i++) {            vis[i] = false;            if(str[i] == '(') {                S.push(i);            }            else {                if(!S.empty()) {                    int v = S.top();                    vis[v] = true;                    S.pop();                    vis[i] = true;                }            }        }        int ans = 0; int res = 0;        for(int i = 0; i < len; i++) {            if(vis[i]) {                res++;            }            else {                ans = max(ans, res);                res = 0;            }        }        ans = max(ans, res);        printf("%d\n", ans);    }    return 0;}
0 0
原创粉丝点击