2705:扩号匹配问题
总时间限制:
1000ms
内存限制:
65536kB
描述
在某个字符串(长度不超过100)中有左括号、右括号和大小写字母;规定(与常见的算数式子一样)任何一个左括号都从内到外与在它右边且距离最近的右括号匹配。写一个程序,找到无法匹配的左括号和右括号,输出原来字符串,并在下一行标出不能匹配的括号。不能匹配的左括号用"$"标注,不能匹配的右括号用"?"标注.
输入
输入包括多组数据,每组数据一行,包含一个字符串,只包含左右括号和大小写字母,字符串长度不超过100
注意:cin.getline(str,100)最多只能输入99个字符!
输出
对每组输出数据,输出两行,第一行包含原始输入字符,第二行由"$","?"和空格组成,"$"和"?"表示与之对应的左括号和右括号不能匹配。
样例输入
((ABCD(x)
)(rttyy())sss)(
样例输出
((ABCD(x)
$$
)(rttyy())sss)(
? ?$
解题思路:
现在一遇到括号匹配问题我就想用栈写:
所以先上一个栈的版本
用栈的思路很简单,如果是左括号就入栈,如果是右括号就判断栈是否为空,若为空也直接如栈,若不为空,就判断栈顶元素是否是左括号。
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
int main (){
string s;
while(cin >> s){
int len = s.length();
int a[305];
for(int i = 0; i < len; i++){
if(s[i] == '(')
a[i] = 1;
else if(s[i] == ')')
a[i] = 2;
else
a[i] = 0;
}
cout << s << endl;
stack<int> sta;
for(int i = 0; i < len; i++){
if(a[i] == 1){
sta.push(i);
s[i] = '$';
}
else if(a[i] == 2)
{
if( sta.empty() ){
sta.push(i);
s[i] = '?';
}
else{
int b = sta.top();
if( a[b] == 1 ){
sta.pop();
s[b] = ' ';
s[i] = ' ';
}
else{
sta.push(i);
s[i] = '?';
}
}
}
else
s[i] = ' ';
}
cout << s << endl;
}
return 0;
}
递归写法、
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
string s;
stack<int> sta;
int len;
int a[105];
void DFS(int i){
if(i == len)
return ;
if(a[i] == 1){
sta.push(i);
s[i] = '$';
DFS(i + 1);
}
else if(a[i] == 2){
if( sta.empty() ){
sta.push(i);
s[i] = '?';
DFS(i + 1);
}
else{
int b = sta.top();
if( a[b] == 1 ){
sta.pop();
s[b] = ' ';
s[i] = ' ';
DFS(i + 1);
}
else{
sta.push(i);
s[i] = '?';
DFS(i + 1);
}
}
}
else{
s[i] = ' ';
DFS(i + 1);
}
}
int main (){
while(cin >> s){
len = s.length();
for(int i = 0; i < len; i++){
if(s[i] == '(')
a[i] = 1;
else if(s[i] == ')')
a[i] = 2;
else
a[i] = 0;
}
while(!sta.empty()) sta.pop();
cout << s << endl;
DFS(0);
cout << s << endl;
}
}