题解 HZOJ 265 括号画家 C/C++

题目传送门:

括号画家 - 题目 - Online Judge (haizeix.com)icon-default.png?t=O83Ahttps://oj.haizeix.com/problem/265就是判断合法括号序列的升级版:找到最长合法括号序列

括号序列合法性判断一般都会用到 栈 结构

遇到左括号入栈,遇到右括号判断是否与栈顶括号匹配

该题我们只需要在出入栈的过程中标记合法括号序列的位置:

((({}[]((([]{()}}))[][]

00011110001111110001111

最后找到最长合法序列即可

标记合法括号序列位置的方法:

在括号匹配后完成如下操作:

1.标记当前遍历位置,即合法左括号位置

2.向前寻找并标记第一个未标记的位置,即合法右括号位置

代码:

#include <stdio.h>
int main()
{
	char s[10001] = { 0 }, t[10001] = { 0 };
	scanf("%s", s);
	int i, l = strlen(s), top = -1, count[10001] = { 0 };
	for (i = 0; i < l; i++)
	{
		if (s[i] == '(' || s[i] == '[' || s[i] == '{') t[++top] = s[i];
		else
		{
			if (top == -1) continue;
			int flag = 1;
			switch (s[i])
			{
			case ')':
				if (t[top] == '(') flag = 1;
				else flag = 0;
				break;
			case ']':
				if (t[top] == '[') flag = 1;
				else flag = 0;
				break;
			case '}':
				if (t[top] == '{') flag = 1;
				else flag = 0;
				break;
			}
			if (flag)
			{
				count[i] = 1;
				int j = i;
				while (count[j]) j--;
				count[j] = 1;
				top--;
			}
			else top = -1;
		}
	}
	int max = 0, c = 0;
	for (i = 0; i < l; i++) if (count[i]) c++, max = c > max ? c : max; else c = 0;
	printf("%d", max);
	//for (i = 0; i < l; i++) printf("%d", count[i]);//测试用
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值