问题描述
在最近的一次编码采访中,我被要求解决一个问题,其中的任务是完成一个函数,该函数通过引用接收堆栈作为参数,并检查传递的堆栈是否为回文。我确实提出了一种方法,但是对我来说这根本不是一个好方法。
我的代码
functions.https.onRequest
解决方法
一种解决方法是弹出一半堆栈,压入另一堆栈并进行比较。例如:
[A,B,C,A] // our stack,where right is top
-> [A,B],[A] // pop A,push A onto temporary stack
-> [A,C],[A,B] // pop B,push 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;
}
,
bool check_palindrome(std::stack<int> &st) {
std::stack<int> temp;
auto initialSize = st.size();
for(size_t i{}; i < initialSize/2; ++i) { temp.push(st.top()); st.pop(); }
if(temp.size() < st.size()) st.pop();
return st == temp;
}
,
我认为这里不需要递归算法,只需将堆栈中的一半元素压入第二个堆栈中,然后弹出两个堆栈中的元素并检查它们是否相同:
int main()
{
vector<int>vec{-1,-2,-3,-1};
stack<int>st;
for(int i = vec.size() - 1; i >= 0; --i) {
st.push(vec[i]);
}
stack<int> temp;
for (size_t i = 0; i < st.size() / 2; i++)
{
temp.push(st.top());
st.pop();
}
if (st.size() != temp.size()) st.pop();
while (!st.empty())
{
if (st.top() != temp.top()) return 1;
st.pop();
temp.pop();
}
return 0;
}