232.用栈实现队列
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() {
int res = this->pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty()&&stOut.empty();
}
};
/**
* 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();
*/
225. 用队列实现栈
队列是有queue.back()的 即返回队尾元素所以 模拟top时候
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
while(--size) {
int temp = que.front() ;
que.pop();
this->push(temp);
}
int result = que.front() ;
que.pop();
return result;
}
int top() {
//int result = this->pop();
// que.push(result);
// return result;
return que.back();
}
bool empty() {
return que.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();
*/
20. 有效的括号
错误代码:
class Solution {
public:
bool isValid(string s) {
stack<int> st;
for(char t:s) {
if(t=='('||t=='['||t=='{') st.push(t);
else if(t=')') {
if(st.empty()||st.top()!='(') return false;
else {
st.pop();
}
}
else if(t=']') {
if(st.empty()||st.top()!='[') return false;
else {
st.pop();
}
}
else {
if(st.empty()||st.top()!='{') return false;
else {
st.pop();
}
}
}
return true;
}
};
1、stack中数据类型是char
2、没有考虑左括号最后多余的情况
3、又把==写成=
正确代码
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(char t:s) {
if(t=='('||t=='['||t=='{') st.push(t);
else if(t==')') {
if(st.empty()||st.top()!='(') return false;
else {
st.pop();
}
}
else if(t==']') {
if(st.empty()||st.top()!='[') return false;
else {
st.pop();
}
}
else {
if(st.empty()||st.top()!='{') return false;
else {
st.pop();
}
}
}
if(st.empty())
return true;
else return false;
}
};
1047. 删除字符串中的所有相邻重复项
1、最后返回的不是s 自己得到栈之后要转成string
2、string result0后,直接result[i++]=st.top(); 会报错
3、对string要不然就初始化st.size()要不然可以使用result+=st.top();
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(char t:s) {
if(st.empty()) st.push(t);
else if (st.top()==t) st.pop();
else{
st.push(t);
}
}
string result;
int size=st.size();
int i=0;
while(size--){
result[i++]=st.top();
st.pop();
}
reverse(result.begin(),result.end());
return result;
}
};
字符串直接当栈使用
class Solution {
public:
string removeDuplicates(string S) {
string result;
for(char s : S) {
if(result.empty() || result.back() != s) {
result.push_back(s);
}
else {
result.pop_back();
}
}
return result;
}
};