每日一题之 hiho228周 Parentheses Matching (简单题)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014046022/article/details/83957830

描述
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;

bool cmp (pair<int,int>a, pair<int,int>b) {
	return a.first < b.first;
}

void solve(string s) {

	stack<pair<char,int>>st;
	vector<pair<int,int>>res;
	int len = s.length();
	for (int i = 0; i < len; ++i) {
		if (s[i] == '(') {
			st.push(make_pair(s[i],i+1));
		}
		else {
			auto now = st.top();
			st.pop();
			res.push_back(make_pair(now.second,i+1));
		}
		
	}

	sort(res.begin(),res.end(),cmp);
	int vlen = (int)res.size();
	for (int i = 0; i < vlen; ++i) {
		cout << res[i].first << " " << res[i].second << endl;
	}

}

int main() {

	string s;
	cin >> s;
	solve(s);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/83957830