栈
今天的算法内容是:栈
一、 每日一题
- 删除最外层括号
- 用stktop变量去判断是不是完整的一组括号
- 如果是完整的一组括号,只取内层的括号。内层如果没有就是空字符串
- pre = i+1 跳到下一组括号,再进行判断,最后返回答案
class Solution {
public:
string removeOuterParentheses(string s) {
string ans;
int stktop = 0;
int pre = 0;
for(int i = 0; i < s.size(); ++i) {
if(s[i] == '(') {
++stktop;
}else {
--stktop;
}
//当碰到完整的括号的时候
if(stktop == 0) {
for(int j = pre+1; j <= i-1; ++j) {
ans += s[j];
}
//判断下一组括号
pre = i+1;
}
}
return ans;
}
};
- 无法吃午餐的学生数量
- 两个变量istu和isand分别记录学生和三明治数组的索引
- 如果索引值相等,就都加1再比较下一组数据;如果不相等,就把学生的索引值的值加到学生数组的尾端,并且索引值加1.
- 要注意的是,需要添加一个limit,用来跳出循环,否则会无限循环下去
- 返回值是学生数组的长度减去学生的索引值。
class Solution {
public:
int countStudents(vector& students, vector& sandwiches) {
int istu = 0;
int isand = 0;
int limit = 0;
while(istu < students.size() && isand < sandwiches.size()) {
if(students[istu] == sandwiches[isand]) {
isand++;
istu++;
}else{
students.push_back(students[istu]);
istu++;
if(limit++>200) break;
}
}
return students.size()-istu;
}
};
- 设计一个支持增量操作的栈
- 用一个数组表示栈的思想
- 用变量top表示栈顶,变量size表示栈的最大长度
class CustomStack {
public:
int top, size;
int *stk;
CustomStack(int maxSize) {
stk = new int[maxSize+1];
size = maxSize;
top = 0;
}
void push(int x) {
if(top < size) {
stk[top++] = x;
}
}
int pop() {
if(top == 0) {
return -1;
}
top--;
return stk[top];
}
void increment(int k, int val) {
if(top < k) {
for(int i = 0; i < top; ++i) {
stk[i] += val;
}
} else {
for(int i = 0; i < k; ++i) {
stk[i] += val;
}
}
}
};