【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 
#include 
using namespace std; 
#define MAXN 100005
char s[MAXN];
int arr[MAXN];

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

你可能感兴趣的:(ACM)