合法出栈序列
给定一个由不同小写字母构成的长度不超过8的字符串x,现在要将该字符串的字符依次压入栈中,然后再全部弹出。
要求左边的字符一定比右边的字符先入栈,出栈顺序无要求。
再给定若干字符串,对每个字符串,判断其是否是可能的x中的字符的出栈序列。
时间限制:1000
内存限制:65536
输入
第一行是原始字符串x 后面有若干行,每行一个字符串
输出
对除第一行以外的每个字符串,判断其是否是可能的出栈序列。如果是,输出"YES",否则,输出"NO"
样例输入
abc
abc
bca
cab
样例输出
YES
YES
NO
#include <iostream>
#include <stack>
#include <queue>
#include <cstring>
bool check_is_valid_order(std::queue<int>& order) {
std::stack<int> S;
int n = order.size();
for (int i = 1; i <= n; i++) {
S.push(i);
while (!S.empty() && order.front() == S.top()) {
S.pop();
order.pop();
}
}
if (!S.empty()) {
return false;
}
return true;
}
int main() {
std::string input;
char org[100];
std::cin >> org;
while (std::cin >> input) {
std::queue<int> order;
for (char ch : input) {
for (int i = 0; i < strlen(org); i++) {
if (org[i] == ch) {
order.push(i + 1);
}
}
}
if (check_is_valid_order(order)) {
std::cout << "YES" << std::endl;
} else {
std::cout << "NO" << std::endl;
}
}
return 0;
}
能不能在简单点
【以下回答由 GPT 生成】
给定一个由不同小写字母构成的长度不超过8的字符串x,现在要将该字符串的字符依次压入栈中,然后再全部弹出。要求左边的字符一定比右边的字符先入栈,出栈顺序无要求。再给定若干字符串,对每个字符串,判断其是否是可能的x中的字符的出栈序列。
这个问题可以转化为栈的出栈序列的问题。我们可以使用一个栈来模拟字符串x的入栈和出栈过程。初始时,栈为空。遍历给定的字符串,并根据当前字符进行以下操作:
最后,如果栈为空,说明给定的字符串是可能的出栈序列,否则不是。
#include <iostream>
#include <string>
#include <stack>
using namespace std;
bool isPossibleOutSequence(const string& sequence, const string& x) {
stack<char> st;
int i = 0;
for (char c : sequence) {
while (!st.empty() && st.top() != c && i < x.length()) {
st.push(x[i++]);
}
if (!st.empty() && st.top() == c) {
st.pop();
} else {
return false;
}
}
return st.empty();
}
int main() {
string x;
cin >> x;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
string sequence;
cin >> sequence;
if (isPossibleOutSequence(sequence, x)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
【相关推荐】