64,172
社区成员




1441. 用栈操作构建数组
解题思路:
先把元素进栈,若不等于target[pos]就出栈;若等于target[pos]就直接退出循环。
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
vector<string> mystack;
int pos = 0;
for(int i = 1; i <= n; ++i) {
mystack.push_back("Push");
if(target[pos] != i) {
mystack.push_back("Pop");
}
else {
if(pos < target.size()) ++pos;
if(pos == target.size()) break;
}
}
return mystack;
}
};
1021. 删除最外层的括号
解题思路:
若遇到 ( 且栈为空的话的话,就代表着这个 ( 是最外层的括号,s中可以删除,然后将 ( 进栈;若栈不为空,将 ( 进栈。若遇到 ) , 之前存着的 ( 出栈;出栈后若栈为空,则该元素是最外层的 ) 括号,s中可以删除。
class Solution {
public:
//括号一定成对
string removeOuterParentheses(string s) {
if(s == "") return "";
stack<char> mystack;
int i = 0;
while(i < s.size())
{
if(s[i] == '(') {
if(mystack.empty()) {
mystack.push('(');
s.erase(s.begin() + i);
}
else if(!mystack.empty()) {
mystack.push('(');
++i;
}
}
if(s[i] == ')') {
mystack.pop();
if(mystack.empty()) {
s.erase(s.begin() + i);
}
else ++i;
}
}
return s;
}
};
1381. 设计一个支持增量操作的栈
解题思路:
用一个vector,支持所有的push_back、pop_back等等的操作,然后按照题意来就行。
class CustomStack {
vector<int> mystack;
int maxSize;
public:
CustomStack(int maxSize) {
this -> maxSize = maxSize;
}
void push(int x) {
if(mystack.size() == maxSize);
else mystack.push_back(x);
}
int pop() {
if(mystack.size() != 0) {
int n = mystack[mystack.size() - 1];
mystack.pop_back();
return n;
}
return -1;
}
void increment(int k, int val) {
if(k < mystack.size()) {
for(int i = 0; i < k; ++i) {
mystack[i] += val;
}
}
else {
for(int i = 0; i < mystack.size(); ++i) {
mystack[i] += val;
}
}
}
};
/**
* Your CustomStack object will be instantiated and called as such:
* CustomStack* obj = new CustomStack(maxSize);
* obj->push(x);
* int param_2 = obj->pop();
* obj->increment(k,val);
*/