再给定若干字符串,判断其是否是可能的x中的字符的出栈序列(相关搜索:字符串输出)

合法出栈序列
给定一个由不同小写字母构成的长度不超过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的入栈和出栈过程。初始时,栈为空。遍历给定的字符串,并根据当前字符进行以下操作:

  • 如果当前字符和栈顶字符相同,说明该字符已经在栈中。将栈顶字符弹出。
  • 如果当前字符和栈顶字符不同,说明该字符还没有入栈。将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;
}

复杂度分析

  • 时间复杂度:对于每个查询,需要遍历字符串两次,最坏情况下时间复杂度为O(n^2),其中n为字符串长度。对于每个字符需要在栈中查找,栈中元素最多为n个。
  • 空间复杂度:需要额外使用一个栈来模拟入栈和出栈过程,空间复杂度为O(n)。


【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^