描述
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
一般括号匹配的变形,错了一发,要把所有情况想清楚再写。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn=110000;
int a[maxn],b[maxn];
int d[maxn];
int v[maxn];
int main()
{
char c[maxn];
scanf("%s",c);
int l=strlen(c);
int ans1=0,ans2=0;
int tem=0;
for(int i=0;i<l;i++)
{
if(c[i]=='(')
{
a[ans1++]=i+1;
tem=ans1-1;
}
else
{
b[ans2++]=i+1;
while(v[tem])
{
tem--;
}
d[tem--]=ans2-1;
v[tem+1]=1;
}
}
for(int i=0;i<ans1;i++)
{
printf("%d %d\n",a[i],b[d[i]]);
}
return 0;
}