第十天 2021-3-12 每日刷四题
刷题模块:栈 - 简单难度
一、STL:stack
函数 | 方法 |
---|---|
top() | 返回一个栈顶元素的引用,类型为 T&。如果栈为空,返回值未定义。 |
push(const T& obj) | 可以将对象副本压入栈顶。这是通过调用底层容器的 push_back() 函数完成的。 |
push(T&& obj) | 以移动对象的方式将对象压入栈顶。这是通过调用底层容器的有右值引用参数的 push_back() 函数完成的。 |
pop() | 弹出栈顶元素。 |
size() | 返回栈中元素的个数。 |
empty() | 在栈中没有元素的情况下返回 true。 |
emplace() | 用传入的参数调用构造函数,在栈顶生成对象。 |
swap(stack & other_stack) | 将当前栈中的元素和参数中的元素交换。参数所包含元素的类型必须和当前栈的相同。对于 stack 对象有一个特例化的全局函数 swap() 可以使用。 |
二、C++ 单引号和双引号
单引号是字符型, 双引号是字符串型
单引号引起的一个字符实际上代表一个整数。
双引号引起的字符串,代表的却是一个指向无名数组起始字符的指针。该数组会被双引号之间的字符以及一个额外的二进制为零的字符 ‘\0’ 初始化。
c++中的 单引号和双引号
应用
char ch="A";
switch(){
// "A" 为字符串,语法报错
case "A":
// 'A' 为字符,正确
case 'A':
}
三、【题】有效的括号
直接放优化过后的代码,做了如下优化,形式和逻辑优化不再提,重点为方法优化。
- 使用unordered_map的键值对来存储括号对,判断时简化了代码量,使逻辑更加清晰,结构更加严谨。
- 使用count()函数而不是find()==end()函数判断使得代码更加简洁。
class Solution {
public:
bool isValid(string s) {
stack<char> Stack;
unordered_map<char,char> hash{{')','(',},{']','['},{'}','{'}};
for(auto &x:s){
if(!hash.count(x)) Stack.push(x);
else if(Stack.empty() || Stack.top()!=hash[x])return false;
else Stack.pop();
}
return Stack.empty();
}
};
四、【题】最小栈
官方解法:使用辅助栈,记录每个元素入栈时,该状态下的最小值
栈只会pop栈顶的元素,辅助栈同时pop栈顶即可
class MinStack {
stack<int> x_stack;
stack<int> min_stack;
public:
MinStack() {
min_stack.push(INT_MAX);
}
void push(int x) {
x_stack.push(x);
min_stack.push(min(min_stack.top(), x));
}
void pop() {
x_stack.pop();
min_stack.pop();
}
int top() {
return x_stack.top();
}
int getMin() {
return min_stack.top();
}
};
面试的时候被问到不能用额外空间,就去网上搜了下不用额外空间的做法。思路是栈里保存差值。
十分的妙
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min_value = -1
def push(self, x: int) -> None:
if not self.stack:
self.stack.append(0)
self.min_value = x
else:
diff = x-self.min_value
self.stack.append(diff)
self.min_value = self.min_value if diff > 0 else x
def pop(self) -> None:
if self.stack:
diff = self.stack.pop()
if diff < 0:
top = self.min_value
self.min_value = top - diff
else:
top = self.min_value + diff
return top
def top(self) -> int:
return self.min_value if self.stack[-1] < 0 else self.stack[-1] + self.min_value
def getMin(self) -> int:
return self.min_value if self.stack else -1
五、【题】用队列实现栈
使用一个队列即可
入栈时,
- 将新元素入队
- 将前面的元素全部重新进入队列
即可保证先进来的元素排在队列的前面
class MyStack {
queue<int> myQueue;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
int n=myQueue.size();
myQueue.push(x);
for(int i=0;i<n;i++){
myQueue.push(myQueue.front());
myQueue.pop();
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int temp=myQueue.front();
myQueue.pop();
return temp;
}
/** Get the top element. */
int top() {
return myQueue.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return myQueue.empty();
}
};
使用两个队列反而将算法变得复杂,强行借助另一个队列来接收旧值