用栈实现队列
原题链接:用栈实现队列
思路:栈的特点是先进后出,将先后顺序反转,如果再反转一次就是正序。将一个栈内元素,全部移到另一个栈中,就可以做到先进先出了。要注意的是,将元素移动的时机,一定是用于输出的栈元素为空。
class MyQueue {
public:
stack<int> input;
stack<int> output;
MyQueue() {
}
void tran(){
while(!input.empty()){
int temp = input.top();
input.pop();
output.push(temp);
}
}
void push(int x) {
input.push(x);
}
int pop() {
if(output.empty()){
tran();
}
int res = output.top();
output.pop();
return res;
}
int peek() {
if(output.empty()) tran();
return output.top();
}
bool empty() {
return input.size()+output.size() == 0;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
用队列实现栈
原题链接:用队列实现栈
思路:由于队列是先进先出,想要弹出最后一个数字,必须将前面全部出列。因此,每次弹出最后一个数字时,可以将size-1个元素出列,在重新入列,这样队列前端的数字为要处理的数字。
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size()-1;
if(size != -1)
{
while(size--){
int x = q.front();
q.pop();
q.push(x);
}
}
int res = q.front();
q.pop();
return res;
}
int top() {
int size = q.size()-1;
if(size != -1)
{
while(size--){
int x = q.front();
q.pop();
q.push(x);
}
}
int res = q.front();
q.pop();
q.push(res);
return res;
}
bool empty() {
return q.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
有效的括号
原题链接:有效的括号
思路:可以发现,"()[]{}"每对都是成对出现且相邻的,我们只需要将左侧存储,当右侧出现时,和左侧最后一个比较。我们需要取左侧最后一个元素,即后入先出,可以使用栈。
class Solution {
public:
bool isValid(string s) {
if(s.size()%2 != 0) return false;
stack<char>st;
unordered_map<char,char>m;
m.insert({')','('});
m.insert({']','['});
m.insert({'}','{'});
for(auto i : s){
if(i=='(' || i=='[' || i=='{'){
st.push(i);
}else{
if(st.empty() || m[i]!= st.top()){
return false;
}
st.pop();
}
}
return st.empty();
}
};
删除字符串中所有相邻重复项
原题链接:删除字符串中的所有相邻重复项
思路:直接按题目意思,容易想到遍历数组,如果它和前一个相同,则删除二者。这样做复杂度太高,在这之上增加一个bool数组,表示该元素是否被删除,这样做可以,但是很麻烦,特别是移动下标时,需要移动到bool为false为止。我们可以使用栈结构,每次入栈时,可以判断栈顶元素是否和入栈元素相同,相同则pop,且不入栈,最后结果输入反转一下即可。
class Solution {
public:
string removeDuplicates(string s) {
stack<char>st;
for(auto i : s){
if(!st.empty() && st.top()==i){
st.pop();
}else{
st.push(i);
}
}
string rs;
while(!st.empty()){
rs+=st.top();
st.pop();
}
reverse(rs.begin(),rs.end());
return rs;
}
};