《五月集训》第14天 栈

Crazy_DM 2022-05-14 16:01:21

1441. 用栈操作构建数组

``````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. 删除最外层的括号

``````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. 设计一个支持增量操作的栈

``````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);
*/``````

...全文
23 回复 打赏 收藏 举报

6.2w+

2022-05-14 16:01

QQ群：480072171