11549: 【原1549】Parentheses Matching Problem
题目
题目描述
author: Online Judge 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/1549
Description
在某个字符串(长度不超过100)中有左括号、右括号和大小写字母;规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右边且距离最近的右括号匹配。写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号。不能匹配的左括号用"$"标注,不能匹配的右括号用"?"标注.
Input Format
输入包括多组数据,每组数据一行,包含一个字符串,只包含左右括号和大小写字母,字符串长度不超过100。
注意:cin.getline(str,100)最多只能输入99个字符!
Output Format
对每组输出数据,输出两行,第一行包含原始输入字符,第二行由"$","?"和空格组成,"$"和"?"表示与之对应的左括号和右括号不能匹配。
Sample Input
)(rttyy())sss)(
Sample Output
)(rttyy())sss)(
? ?$
ligongzzz's solution
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;
using pic = pair<int, char>;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string ch;
while (cin >> ch) {
stack<pic> sdata;
auto length = ch.length();
vector<char> vdata(length, ' ');
for (int i = 0; i < length; ++i) {
if (ch[i] == '(') {
sdata.push(make_pair(i, '('));
}
else if (ch[i] == ')') {
if (!sdata.empty() && sdata.top().second == '(') {
sdata.pop();
}
else{
sdata.push(make_pair(i,')'));
}
}
}
while (!sdata.empty()) {
vdata[sdata.top().first] = sdata.top().second == '(' ? '$' : '?';
sdata.pop();
}
cout << ch << "\n";
for (auto p : vdata)
cout << p;
cout << "\n";
}
return 0;
}
yyong119's solution
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
char str[110],cha[110];
int point;
int main() {
while (scanf("%s", str) != EOF) {
point = 0;
int len = strlen(str);
for (int i = 0; i < len; ++i) {
cha[i] = ' ';
if (str[i] == '(') ++point;
if (str[i] == ')') {
--point;
if (point < 0) {
point = 0; cha[i] = '?';
}
}
}
point = 0;
for (int i = len - 1; i >= 0; --i) {
if (str[i] == ')') ++point;
if (str[i] == '(') {
--point;
if (point < 0) {
point = 0; cha[i] = '$';
}
}
}
printf("%s\n%s\n", str, cha);
}
}