欢迎大家积极在评论区留言发表自己的看法,知无不言,言无不尽,养成每天刷题的习惯,也可以自己发布优质的解题报告,供社区一同鉴赏,吸引一波自己的核心粉丝。
今天是七月集训第十四天:栈
1614. 括号的最大嵌套深度
剑指 Offer 06. 从尾到头打印链表
1381. 设计一个支持增量操作的栈
1441. 用栈操作构建数组
// 1614. 括号的最大嵌套深度
class Solution {
public:
int maxDepth(string s) {
int ans = 0, cnt = 0;
for (auto& ch : s)
{
if (ch == '(')
cnt++;
else if (ch == ')')
cnt--;
ans = max(ans, cnt);
}
return ans;
}
};
// 剑指 Offer 06. 从尾到头打印链表
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> ans;
while(head != nullptr) {
ans.emplace_back(head->val);
head = head->next;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
// 1381. 设计一个支持增量操作的栈
class CustomStack {
vector<int> stack;
int top;
public:
CustomStack(int maxSize) {
stack = vector<int>(maxSize + 1);
top = 0;
}
void push(int x) {
if(top < stack.size() - 1){
stack[top++] = x;
}
}
int pop() {
int x = -1;
if(top > 0) {
x = stack[--top];
}
return x;
}
void increment(int k, int val) {
int n = stack.size();
if(n < k) {
for(int i = 0; i < n; ++i) {
stack[i] += val;
}
} else {
for(int i = 0; i < k; ++i) {
stack[i] += val;
}
}
}
};
// 1441. 用栈操作构建数组
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
int len = target.size(), limit = target.back();
int hash[101];
memset(hash, 0, sizeof(hash));
vector<string> ans;
for(int i = 0; i < len; ++i) {
hash[target[i]]++;
}
for(int i = 1; i <= limit; ++i) {
ans.emplace_back("Push");
if(!hash[i]) {
ans.emplace_back("Pop");
}
}
return ans;
}
};