我不受限制,我使我自己自由,我走到我所愿去的任何地方。
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 ret = this->pop();
stOut.push(ret);
return ret;
}
bool empty() {
return stIn.empty() &&stOut.empty();
}
};
- 时间复杂度: 都为O(1)。pop和peek看起来像O(n),实际上一个循环n会被使用n次,最后还是O(1)。
- 空间复杂度: O(n)
- 不太理解pop()中的stIn.pop()和stOut.pop()操作的作用和意义
225. 用队列实现栈
两个队列:
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int size = que1.size();
size--;
while (size--) {
que2.push(que1.front());
que1.pop();
}
int result = que1.front();
que1.pop();
que1 = que2;
while (!que2.empty()) {
que2.pop();
}
return result;
}
int top() {
int size = que1.size();
size--;
while (size--) {
que2.push(que1.front());
que1.pop();
}
int result = que1.front();
que2.push(que1.front());
que1.pop();
que1 = que2;
while (!que2.empty()) {
que2.pop();
}
return result;
}
bool empty() {
return que1.empty();
}
};
- 时间复杂度: pop为O(n),top为O(n),其他为O(1)
- 空间复杂度: O(n)
- 思路很重要, 理解了整个过程的思路, 代码就能慢慢写出来
一个队列:
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() {
return que.back();
}
bool empty() {
return que.empty();
}
};
- 时间复杂度: pop为O(n),top为O(n),其他为O(1)
- 空间复杂度: O(n)
- 一个队列的实现也比较好理解
20. 有效的括号
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() || st.top() != s[i]) return false;
else st.pop();
}
return st.empty();
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(n)
- 很难去把问题归为这三类, 感觉题目都没看明白.
1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string S) {
stack<char> st;
for (char s : S) {
if (st.empty() || s != st.top()) {
st.push(s);
}
else {
st.pop();
}
}
string result = "";
while (!st.empty()) {
result += st.top();
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
};
- 时间复杂度: O(n)
- 空间复杂度: O(n)
- 这题思路是对的,但是代码没写对

739

被折叠的 条评论
为什么被折叠?



