gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:06:55 25 4
gpt4 key购买 nike

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com