Acy夕拾算法 Week1_day4
LeetCode 20. 有效的括号
/*
整理思路:
·左括号必须以正确顺序闭合,用栈,先进后出,确保顺序闭合
·放入栈时,不放左括号本身,而是放对应的右括号–方便查询和弹出
·遍历,如果是({[,放入]});如果等于栈顶,弹出栈顶;都不对应,无效括号false
·错误:没考虑到 “){” ----栈顶为空时,return false;
·剪枝:字符串为奇数,一定不是有效字符串,括号两两对应
*/
class Solution {
public:
bool isValid(string s) {
stack<char> st;
if(s.size() % 2 != 0) return false;//剪枝
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '(') st.push(')');
else if(s[i] == '{') st.push('}');
else if(s[i] == '[') st.push(']');
else if(st.empty() == 1) return false;//有前后顺序
else if(s[i] == st.top()) st.pop();//有前后顺序--top是st必须不为空
else//不对应
return false;
}
return st.empty();
}
};
LeetCode 232. 用栈实现队列
/*
·实际pop无返回值
我的思路:
·两个栈,temp_stack中转栈,queue_stack队列先进先出栈
··eg: abc先放入temp_stack:栈顶-cba-栈底;
······这些做完,top&push到queue_stack:栈顶-abc-栈底;
·先push放入temp_stack中转栈; 把temp_stack的top,push到queue_stack里,同时temp_stack pop掉
·(需优化)得到pop/peek后再把queue_stack全部放回temp_stack---------下面改进
优化点:
·不必重新放回,当queue_stack为空时,再导入temp_stack即可----因为出队列,只有在前面的全部出完,才会轮到后面;
··这样就相当于:队尾(temp栈顶) ==|== 队头(queue栈顶),65|4321
··eg:push 1234; pop3:1、2、3; push 56; pop3:4、移动、5、6
··eg: 4321|_ -> |4321 -> 65|4 -> 65| -> _|65 -> |
·peek时复用pop,不要重复写
*/
class MyQueue {
stack<int> temp_stack;
stack<int> queue_stack;
public:
MyQueue() {
}
void push(int x) {
temp_stack.push(x);
}
int pop() {
int temp, res;
if(queue_stack.empty())
{
while( !temp_stack.empty() )
{
temp = temp_stack.top();
queue_stack.push(temp);
temp_stack.pop();
}
}
res = queue_stack.top();
queue_stack.pop();
return res;
}
int peek() {
int res = this->pop(); //this->使用已有函数
queue_stack.push(res);
return res;
}
bool empty() {
return queue_stack.empty()&&temp_stack.empty();
}
};
LeetCode 225. 用队列实现栈
方法一:两个队列
/*
栈、队列有.size()
我的思路:
两个队列,需要弹出时,把所有前面的都放进temp队列,size()-1次放入,最后一个直接pop不push
*/
class MyStack {
queue<int> stack_que;
queue<int> temp_que;
public:
MyStack() {
}
void push(int x) {
stack_que.push(x);
}
int pop() {
int res, size = stack_que.size() - 1;//最后一个不push----
while(size--)
{
res = stack_que.front();
temp_que.push(res);
stack_que.pop();
}
res = stack_que.front();//最后一个不push------------------
stack_que.pop();
stack_que = temp_que;//直接就能放 //再放回来
while(!temp_que.empty())
{//清空
temp_que.pop();
}
return res;
}
int top() {
int res = this->pop();
stack_que.push(res);
return res;
}
bool empty() {
return stack_que.empty();
}
};
方法二:一个队列
/*
优化:
一个队列;从队头到队尾重排,只改pop就好
*/
class MyStack {
queue<int> stack_que;
public:
MyStack() {
}
void push(int x) {
stack_que.push(x);
}
int pop() {
int res, size = stack_que.size() - 1;//最后一个pop掉----
while(size--)
{
res = stack_que.front();
stack_que.push(res);//重新入队
stack_que.pop();
}
res = stack_que.front();//最后一个pop掉------------------
stack_que.pop();
return res;
}
int top() {
int res = this->pop();
stack_que.push(res);
return res;
}
bool empty() {
return stack_que.empty();
}
};
队列有.back()返回队尾的方法
int top() {
return stack_que.back();//C++:back()可以直接返回队尾
}