Skip to content

M03704: 扩号匹配问题

Stack, http://cs101.openjudge.cn/pctbook/M03704/

在某个字符串(长度不超过100)中有左括号、右括号和大小写字母;规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右边且距离最近的右括号匹配。写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号。不能匹配的左括号用"$"标注,不能匹配的右括号用"?"标注.

输入

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

输出

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

样例输入

((ABCD(x)
)(rttyy())sss)(

样例输出

((ABCD(x)
$$
)(rttyy())sss)(
?            ?$

题目里说“字符串长度不超过 100”,但 cin.getline(str, 100) 最多只能读 99 个字符,再加上 '\0'

  1. 数组开大一位:用 char str[101];char accord[101];,避免越界。
  2. getline 读 101cin.getline(str, 101),这样能读入 100 个字符 + 末尾 \0
  3. accord 初始化:初始化时一定要覆盖到 [0..length-1],不然可能带有上一次循环的数据。
cpp
#include <iostream>
#include <string>
#include <stack>
#include <cstring>
using namespace std;

int main() {
    char str[101]; // 开大一位,避免越界
    while (cin.getline(str, 101)) { // 改为 101
        int length = strlen(str);
        stack<int> err;
        char accord[101]; // 同样开大一位

        // 初始化 accord 数组
        for (int i = 0; i < length; i++) {
            accord[i] = ' ';
        }

        for (int i = 0; i < length; i++) {
            if (str[i] == '(') {
                err.push(i);
            }
            else if (str[i] == ')') {
                if (!err.empty()) {
                    err.pop();
                }
                else {
                    accord[i] = '?';
                }
            }
        }

        while (!err.empty()) {
            int position = err.top();
            err.pop();
            accord[position] = '$';
        }

        cout << str << endl;
        for (int i = 0; i < length; i++) {
            cout << accord[i];
        }
        cout << endl;
    }
    return 0;
}