LeetCode題目鏈接
https://leetcode.cn/problems/implement-queue-using-stacks/
https://leetcode.cn/problems/implement-stack-using-queues/description/
https://leetcode.cn/problems/valid-parentheses/description/
https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/description/
題解
232.用棧實現隊列
難度不大。
225.用隊列實現棧
與上題類似。
20.有效的括號
有提示用棧了,不然可能不知道怎么寫吧。
1047.刪除字符串中的所有相鄰重復項
用棧的思想真是太巧妙了,完全不知道怎么寫。用棧非常簡單。
學到了當棧里存的字符串是相反的時,只要reverse一下就可以了,代碼如下:
reverse (result.begin(), result.end());
代碼
//232.用棧實現隊列
#include <iostream>
#include <stack>
using namespace std;class MyQueue {
public:MyQueue() {// 不需要在構造函數中重新聲明棧,應該在類中聲明它們}void push(int x) {while (!s1.empty()) {int tmp = s1.top();s2.push(tmp);s1.pop();}s1.push(x);while (!s2.empty()) {int tmp = s2.top();s1.push(tmp);s2.pop();}}int pop() {int result = s1.top();s1.pop();return result;}int peek() {return s1.top();}bool empty() {if (s1.empty() && s2.empty()) return true;else return false;}
private:stack<int> s1, s2;
};int main() {MyQueue obj;obj.push(1);obj.push(2);cout << obj.peek() << endl;cout << obj.pop() << endl;cout << obj.empty() << endl;return 0;
}
//225.用隊列實現棧
#include <iostream>
#include <queue>
using namespace std;class MyStack {
public:MyStack() {}void push(int x) {while (!q1.empty()) {q2.push(q1.front());q1.pop();}q1.push(x);while (!q2.empty()) {q1.push(q2.front());q2.pop();}}int pop() {int result = q1.front();q1.pop();return result;}int top() {return q1.front();}bool empty() {if (q1.empty() && q2.empty()) return true;else return false;}
private:queue<int> q1, q2;
};int main() {MyStack obj;obj.push(1);obj.push(2);cout << obj.top() << endl;cout << obj.pop() << endl;cout << obj.empty() << endl;return 0;
}
//20.有效的括號
#include <iostream>
#include <stack>
using namespace std;class Solution {
public:bool isValid(string s) {stack<char> st;for (char c : s) {if (c == '(' || c == '[' || c == '{') st.push(c);else {if (st.empty()) return false;if ((c == ')' && st.top() == '(') || (c == ']' && st.top() == '[') || (c == '}' && st.top() == '{'))st.pop();else return false;}}if (!st.empty()) return false;return true;}
};int main() {Solution s;string str = "]";printf("%d", s.isValid(str));return 0;
}
//1047.刪除字符串中的所有相鄰重復項
#include <iostream>
#include <stack>
#include <string>
using namespace std;class Solution {
public:string removeDuplicates(string s) {stack<char> st;string result, tmp;for (char c : s) {if (st.empty() || st.top() != c) st.push(c);else if (st.top() == c) st.pop();}while (!st.empty()) {tmp += st.top();st.pop();};for (int i = tmp.size() - 1;i >= 0;i--) {result += tmp[i];}return result;}
};int main() {string str = "abbaca";Solution s;cout << s.removeDuplicates(str) << endl;return 0;
}