天天看点

c++括号匹配问题

问题:
(1)23(4()5)6
输出所输入内容中的括号对的对数,并且输出相应括号对的序号。
输出内容应该如下:
3
0 2
5 10
7 8
           

此题要从栈入手!

#include <iostream>
#include <vector>
#include <stack>
#include<string>
#include<algorithm>
using namespace std;


int main() {
	string s;
	cin >> s;

	stack<int>st;
	
	vector<pair<int,int > > res;
	int count = 0;
	for (int i = 0;i < s.size();i++)
	{
		if(s[i]=='(')
		{
			st.push(i);
			count++;
		}
		if (s[i] == ')')
		{
			pair<int, int> p;
			int tmp = st.top();
			st.pop();
			p.first = tmp;
			p.second = i;
			res.push_back(p);
			//cout << tmp << " " << i << endl;

		}
		

	}
	cout << count << endl;
	for (int i = 0;i < res.size();i++)
	{
		cout << res[i].first << " " << res[i].second << endl;
	}
	

	system("pause");
	return 0;
}
           
c++

继续阅读