232.用栈实现队列
利用两个栈进行操作,类的设计是我的弱项,还得练
class MyQueue {
public:
stack<int> stkA;
stack<int> stkB;
MyQueue() {
}
void push(int x) {
stkA.push(x);
}
int pop() {
int topB = peek();
stkB.pop();
return topB;
}
int peek() {
if(stkB.empty()){
while(!stkA.empty()){
int topA = stkA.top();
stkB.push(topA);
stkA.pop();
}
}
int topB = stkB.top();
return topB;
}
bool empty() {
return stkA.empty() && stkB.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. 用队列实现栈
也是使用两个队列来操作,需要注意的是要操作时要清空不空队列。
使用一个队列貌似也行,技巧确实好,看样子脑子还有待提高。
class MyStack {
public:
queue<int> queueA;
queue<int> queueB;
MyStack() {
}
void push(int x) {
if(queueA.empty() && (!queueB.empty())){ // 两个容器,每次只能有一个容器有数据
queueB.push(x);
}else{
queueA.push(x);
}
}
int pop() {
int topQ = 0;
// 将元素从有元素的容器移动到空容器,最后移动的元素为所需元素
if(queueA.empty()){
while(!queueB.empty()){
topQ = queueB.front();
if(queueB.size() > 1){
queueA.push(topQ);
}
queueB.pop();
}
}else if(queueB.empty()){
while(!queueA.empty()){
topQ = queueA.front();
if(queueA.size() > 1){
queueB.push(topQ);
}
queueA.pop();
}
}
return topQ;
}
int top() {
int topQ = this->pop();
if(!queueA.empty()){
queueA.push(topQ);
}else{
queueB.push(topQ);
}
return topQ;
}
bool empty() {
return queueA.empty() && queueB.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<char> stk;
unordered_map<char, char> mp({make_pair('}', '{'), make_pair(')', '('), make_pair(']', '[')});
for(char ca : s){
if(ca == '{' || ca == '[' || ca == '('){
stk.push(ca);
}else{
if(!stk.empty() && mp[ca] == stk.top()){
stk.pop();
}else{
return false;
}
}
}
if(stk.empty()){
return true;
}
return false;
}
};
1047. 删除字符串中的所有相邻重复项
1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
class Solution {
public:
string removeDuplicates(string s) {
stack<char> stk;
for(char ca : s){
if(!stk.empty() && stk.top() == ca){
stk.pop();
}else{
stk.push(ca);
}
}
string ans;
while(!stk.empty()){
ans += stk.top();
stk.pop();
}
reverse(ans.begin(), ans.end());
return ans;
}
};
554

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



