括号匹配并标注(栈)

题目描述:

在某个字符串(长度不超过100)中有左括号、右括号和大小写字母;

规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右边且距离最近的右括号匹配。

写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号。

不能匹配的左括号用"$“标注,不能匹配的右括号用”?"标注.

输入:

输入包括多组数据,每组数据一行,包含一个字符串,只包含左右括号和大小写字母,字符串长度不超过100。
注意:cin.getline(str,100)最多只能输入99个字符!

输出:

对每组输出数据,输出两行,第一行包含原始输入字符,第二行由$,?和空格组成,$和?表示与之对应的左括号和右括号不能匹配。

 

样例输入:

)(rttyy())sss)(

样例输出:

)(rttyy())sss)(

?                ? $

 

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


void clearStack(stack<char>& s) {
    while(!s.empty()) {
        s.pop();
    }
}
void print(stack<char> s) {
    while(!s.empty()) {
        char t = s.top();
        cout << t << " ";
        s.pop();
    }
}


int main() {

    /*
    括号匹配 思想:
    str存放: )(rttyy())sss)(
    res存放结果

    遍历str
    如果str是非(),res += ''
    如果str是(,入栈
    如果str是),
     栈空:说明匹配不上 res+='?';
     栈不空:里面全是'(', 说明匹配上了  s.pop; res+=' ';


     这个题目有点问题:他不会找到完全不匹配的内容
     如果:   fdafda((((()
        他会              $
        而不是      ????   $
    */


    stack<char> s;
    string str;
    string res;
    while(cin >> str) {

        // 清空栈
        clearStack(s);
        res = "";

        for (int i = 0; i <= str.size() - 1 ; i++) {
            if (str[i] != '(' && str[i] != ')') {
                res += ' ';
            } else if (str[i] == '(') {
                s.push(str[i]);
                res += ' ';
            } else if (str[i] = ')') {
                if (s.empty()) {
                    res += '?';
                } else {
                    res += ' ';
                    s.pop();
                }
            }
        }

        if (!s.empty()) {
            res += '$';
        }
        cout << res << endl;

    }
}



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

stack<char> s;
string str;
string str2;

// 这个忘了写!!
void clearStack(){
	while (s.size() > 0){
		s.pop();
	}
} 


int main() {
	while(cin >> str) {
		clearStack();
		str2 = str;
		for (int i = 0; i <= str.size() - 1; i ++) {
			//cout << "fenxi:" << i <<" -- " << str[i] << endl;
			if (str[i] == '(') {
				s.push('(');
				str2[i] = ' ';
			} else if (str[i] == ')') {
				if (s.empty() || s.top() != '(') {
					str2[i] = '?';
				} else if (s.top() == '(') {
					s.pop();
					str2[i] = ' ';
				}
			} else {
				str2[i] = ' ';
			}

		}
		
		if (s.size() > 0){
			str2[str2.size() - 1] = '$';
		}
		cout << str2 << endl;

	}

	return 0;

}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值