题目不难,用栈进行操作:
1.如果
碰到左括号
则
左括号入栈
2.如果碰到右括号
如果栈空
则说明少左括号 直接输出 NO
遍历一遍后
如果栈中还有数据
那就说明少右括号 也输出 NO
最后 输出 YES 即可
下面是代码,仅供参考:
#include <iostream>
#include <stack>
using namespace std;
int a[105];
void f(string s) {
stack<int> st;
for (int i = 0; s[i]; i ++) {
if (s[i] == '(')
st.push(i);
else if (s[i] == ')') {
if (st.empty()) {
a[i] = 2;
} else
st.pop();
}
}
while (!st.empty()) {
a[st.top()] = 1;
st.pop();
}
}
int main() {
string s;
while (cin >> s) {
memset(a, 0, sizeof a);
cout << s << endl;
f(s);
for (int i = 0; s[i]; i ++) {
if (a[i] == 1)
cout << '$';
else if (a[i] == 2)
cout << '?';
else
cout << " ";
}
cout << endl;
}
return 0;
}