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

本文详细解析了如何使用栈来解决括号匹配问题,通过一个简单的C++代码示例,展示了如何找出并排序所有匹配的括号对。适用于初学者理解和掌握栈的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值