hiho228 Parentheses Matching

版权声明:转载我的原创博客情注明出处 https://blog.csdn.net/qq_31964727/article/details/83933183

目录

题目1 : Parentheses Matching

题意分析:

1.题是什么?

2.思路

3.ac代码


题目1 : Parentheses Matching

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

Given a string of balanced parentheses output all the matching pairs.

输入

A string consisting of only parentheses '(' and ')'. The parentheses are balanced and the length of the string is no more than 100000.

输出

For each pair of matched parentheses output their positions in the string.

样例输入

(())()()

样例输出

1 4  
2 3  
5 6  
7 8

题意分析:

1.题是什么?

    就是给你一堆只由左右括号组成的字符串s,长度小于1e5,让你从左到右配对(输入保证肯定是一一配对的),记录配对的左右括号的位置.最后根据左括号位置从小到大输出位置对.

2.思路

    签到题做起来还是很舒服的,直接从左到右扫描字符串,准备好一个栈,我用数组模拟的,遇到左括号就将他位置压进栈,遇到右括号就将栈顶的左括号位置出栈与之配对.注意!!!边配对边输出答案顺序是不对的.

    我的做法是做一个ans数组保存答案,ans数组处理完之后的效果为:

                若字符串中i位置是'(',ans[i]值为与之配对的右括号位置,

                若字符串中i位置是')',ans[i]值为-1

具体实现有点技巧,就是while中else里面那两行

3.ac代码

#include <stdio.h>
const int maxn=1e5+3;
char s[maxn];
int ans[maxn];
int pos[maxn/2],num;

int main(){
	scanf("%s",&s);
	
	num=0;
	int index=0;
	while(s[index]){
		if(s[index]=='(') pos[num++]=index; 
		else{
			ans[index]=-1;
			ans[pos[--num]]=index;
		}
		index++;
	}
	
	for(int i=0;i<index;i++) if(~ans[i]) printf("%d %d\n",i+1,ans[i]+1); 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_31964727/article/details/83933183