c++ - 检查堆栈是否是回文

标签 c++ algorithm stack palindrome stdstack

在最近的一次编码采访中,我被要求解决一个问题,即任务是完成一个功能,该功能通过引用接收堆栈作为自变量,并检查传递的堆栈是否是回文。我确实提出了一种方法,但是对我来说,这根本不是一个好的方法。
我的密码

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

void copy_it(stack<int> &st, stack<int> &temp) {
    if(st.empty())
        return;
    int element = st.top();
    temp.push(element);
    st.pop();
    copy_it(st, temp);
    st.push(element);
}
bool check_palindrome(stack<int> &st, stack<int> &temp) {
    if(st.size() != temp.size())
        return false;
    while(!st.empty()) {
        if(st.top() != temp.top())
            return false;
        st.pop();
        temp.pop();
    }
    return true;
}
int main()
{
    vector<int>vec{-1, -2, -3, -3, -2, -1};
    stack<int>st;
    for(int i = vec.size() - 1; i >= 0; --i) {
        st.push(vec[i]);
    }
    stack<int> temp;
    copy_it(st, temp);
    cout << check_palindrome(st, temp);
   return 0;
} 
有一个更好的方法吗?我最好在寻找递归算法/代码。

最佳答案

一种解决方法是弹出一半堆栈,压入另一堆栈并进行比较。例如:

   [A, B, C, B, A]       // our stack, where right is top
-> [A, B, C, B], [A]     // pop A, push A onto temporary stack
-> [A, B, C], [A, B]     // pop B, push B
-> [A, B], [A, B]        // pop C, discard C
仅当堆栈大小为奇数时,我们才必须弹出回文中心(C)作为最后一步。
bool isPalindrome(std::stack<int> &stack) {
    std::stack<int> tmp;
    size_t size = stack.size();
    size_t halfSize = size / 2;
    for (size_t i = 0; i < halfSize; ++i) {
        tmp.push(stack.top());
        stack.pop();
    }
    // discard leftover element if the number of original elements is odd
    if (size & 1) {
        stack.pop();
    }
    return tmp == s;
}
如果应该恢复原始堆栈的状态,我们只需要通过从tmp堆栈弹出并推回输入stack来逆转该过程。请记住,我们然后不丢弃中间元素,而是暂时存储它,然后再将其推回。
或者,如果不认为这是“作弊”,我们可以简单地接受stack作为值而不是左值引用。然后,我们仅在进行任何更改之前将其复制。
替代递归实现
// balance() does the job of popping from one stack and pushing onto
// another, but recursively.
// For simplicity, it assumes that a has more elements than b.
void balance(std::stack<int> &a, std::stack<int> &b) {
    if (a.size() == b.size()) {
        return;
    }
    if (a.size() > b.size()) {
        b.push(a.top());
        a.pop(); 
        if (a.size() < b.size()) {
            // we have pushed the middle element onto b now
            b.pop();
            return;
        }
    }
    return balance(a, b);
}

bool isPalindrome(std::stack<int> &stack) {
    std::stack<int> tmp;
    balance(stack, tmp);
    return stack == tmp;
}

关于c++ - 检查堆栈是否是回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63661689/

相关文章:

c++ - MFC 中是否有一个标准的目录浏览器对话框,不涉及用户创建目录以指定尚不存在的目录?

c++ - 在构造函数 C++ 标准中修改 const 吗?

algorithm - 证明特定矩阵存在

python - 生成所有可能的三连通图

algorithm - 这个递归函数是迭代的吗?

java - 如何编写接受堆栈和队列的方法?

C++通过连接变量名获取变量值

c++ - 从目录 C++ 打开多个文件

c - 在 C 中使用堆栈反转句子

pandas - 使用熔化、堆栈和多索引 reshape 数据框?