【发布时间】:2020-12-28 18:42:02
【问题描述】:
这是一个问题: 如果可以通过将字符 + 和 1 插入到该序列中来获得正确的算术表达式,则该括号序列称为正则。例如,序列 (())()、() 和 (()(())) 是正则的,而 )(、(() 和 (()))( 则不是。我们称正则括号序列“RBS ”。
给定一个由 n 个字符 (, ) 和/或 ? 组成的序列 s。此序列中恰好有一个字符(也正好是一个字符)。
你必须替换每个字符?使用 ) 或 ((不同的字符 ? 可以用不同的括号替换)。您不能重新排序字符、删除它们、插入其他字符,并且每个 ? 都必须替换。
确定在这些替换之后是否有可能获得平衡序列。
前:
5
()
(?)
(??)
??()
)?(?
输出:
YES
NO
YES
YES
NO
这是我的代码:
#include <bits/stdc++.h>
using namespace std;
bool checkValidString(string s) {
stack<char>st;
for(int i=0;i<s.length();i++)
{
if(!st.empty() && (((st.top() == '(') && s[i] == '?') || ((st.top() == '?') && s[i] == ')') || st.top() == '(' && s[i] == ')'))
{
st.pop();
}
else
{
st.push(s[i]);
}
}
if(st.empty())
{
return true;
}
int si = st.size();
bool odd = false;
if(si%2!=0)
{
odd = true;
}
while(!st.empty())
{
char c = st.top();
if(c!='?')
{
return false;
}
st.pop();
}
if(odd)
{
return false;
}
return true;
}
int main() {
// your code goes here
int n;
cin>>n;
while(n--)
{
string s;
cin>>s;
bool ans = checkValidString(s);
if(ans == 1)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
return 0;
}
但是它给出了错误的答案,你能帮助我哪里出错了吗?谢谢。
【问题讨论】:
-
您的代码是否通过了任何测试用例?哪个测试用例没有通过?
-
@largest_prime_is_463035818 测试用例被隐藏
-
我的意思是你写的测试用例
标签: c++ string algorithm data-structures stack