括号匹配问题

题目

分析

开一个栈来记录左括号位置,而不是记录左括号。扫描原字符串,遇到右括号,查看栈是否空,若不空则匹配,若空则不匹配。扫描结束后,查看栈是否为空,若不空,则栈中存放的是未匹配的的左括号。

代码

 1 #include<iostream>
 2 #include<string>
 3 #include<stack>
 4 using namespace std;
 5 
 6 int main(){
 7     string s;
 8     while(cin>>s){
 9         stack<int>stk; //保存括号在原字符串中的下标
10         string res(s.size(),' ');
11         for(int i = 0;i<s.size();i++){
12             if(s[i] == '('){
13                 stk.push(i);
14             }else if(s[i] == ')'){
15                 if(!stk.empty())
16                     stk.pop();
17                 else 
18                     res[i] = '?';
19             }
20         }
21         while(!stk.empty()){
22             res[stk.top()] = '$';
23             stk.pop();
24         }
25         cout<<s<<endl;
26         cout<<res<<endl;
27     }
28 }
原文地址:https://www.cnblogs.com/fresh-coder/p/14496750.html