今天是6.9,正值端午假期,没啥事把昨天的博客补一下吧,,
每道题的方法:
最后总结写
题目一链接:232. 用栈实现队列 - 力扣(LeetCode)
思路:此题用了两个栈来实现队列的操作,具体是用两个开口相反的栈实现,当stout栈为空时,stin栈里的元素全部进入stout,然后依次输出。
代码:
class MyQueue {
public:
stack<int> stin;
stack<int> stout;
MyQueue() {
}
void push(int x) {
stin.push(x);
}
int pop() {
if(stout.empty()) {
while(!stin.empty()) {
stout.push(stin.top());
stin.pop();
}
}
int result = stout.top();
stout.pop();
return result;
}
int peek() {
if(stout.empty()) {
while(!stin.empty()) {
stout.push(stin.top());
stin.pop();
}
}
int res = stout.top();
return res;
}
bool empty() {
return stin.empty() && stout.empty();
}
};
难点:区分stin.top()和stin.pop()的区别,pop()既能返回值也可以删除栈顶元素
题目二链接:225. 用队列实现栈 - 力扣(LeetCode)
思路:用一个队列就能实现,将队列前面的元素弹出在重新加入队列的末尾即可,最后弹出队前元素。
代码:
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size --;
while(size --) {
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
int top() {
int result = que.back();
return result;
}
bool empty() {
return que.empty();
}
};
难点:
解释细节1:让cur1提前移动的目的是使得两个链表的末尾对齐,使得两个指针对应起来。
题目三链接:20. 有效的括号 - 力扣(LeetCode)
思路:当为左括号时,往栈里加入对应的符号,当是右括号时,比较栈顶和数组元素,此时有两种情况返回false,但如果对应上了就pop,然后接着比较,当数组遍历完最后看栈是否为空
代码:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
if(st.size() % 2 != 0) return false;
else {
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() || st.top() != s[i]) return false;
//如果匹配上了就弹出栈顶元素
else st.pop();
}
//最后如果栈为空则返回true
return st.empty();
}
}
};
难点:
解释细节2:当时右括号时如果st是空或者不相等时返回false,否则就pop
解释细节4:最后如果是空栈,则返回true
题目四链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
思路:把字符串按规则压进栈中,然后利用字符串加和的方法把栈中元素加入到字符串中,然后返回字符串。
代码:
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(int i = 0;i < s.size();i ++) {
if(st.empty() || st.top() != s[i]) st.push(s[i]);
else {
st.pop();
}
}
string result = "";
while(!st.empty()) {
//字符串直接加和
result += st.top();
st.pop();//单纯弹出
}
//别忘了反转字符串
reverse(result.begin(),result.end());
return result;
}
};
难点:
解释细节1:这样可以方便输出答案
解释细节2:因为正着输出正好相反