1. 程式人生 > >每日一題之 hiho228周 Parentheses Matching (簡單題)

每日一題之 hiho228周 Parentheses Matching (簡單題)

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