问题描述
题目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
算法思路
‘)’每次与最近的未配对的’(‘配对,只需要维护一个栈即可。
全部代码
#include <iostream>
#include <stack>
using namespace std;
char str[100002];
int match[100002];
int main()
{
cin >> str;
stack<int> s;
int index = 0;
while (str[index]) {
if (str[index] == '(')
s.push(index);
else if (str[index] == ')'){
match[s.top()] = index+1;
s.pop();
}
++index;
}
for (int i = 0;i < index;++i)
if (match[i] > 0)
cout << i+1 << ' ' << match[i] << endl;
return 0;
}