【HihoCoder 1458 --- Parentheses Matching】栈水题

【HihoCoder 1458 --- Parentheses Matching】栈水题


Description

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

Input

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

Output

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

Sample Input

(())()()

Sample Output

1 4
2 3
5 6
7 8

题意

括号匹配,按顺序输出每对括号的左右括号下标。

解题思路

通过栈,匹配左右括号的下标。然后通过数组映射,按顺序输出。

AC代码:

#include 
#include 
#include 
using namespace std;
const int MAXN = 100005;
char s[MAXN];
int arr[MAXN];

int main()
{
    scanf("%s",s);
    int n=strlen(s);
    stack<int> sta;
    for(int i=0;i<n;i++)
    {
        if(s[i]=='(')
            sta.push(i);
        else
        {
            int x = sta.top();
            sta.pop();
            arr[x]=i;
        }
    }
    for(int i=0;i<n;i++)
        if(s[i]=='(')
            cout << i+1 << " " << arr[i]+1 << endl;
    return 0;
}

你可能感兴趣的:(ACM)