学习内容:
字符串转换整数 (atoi)
class Solution {
public:
int myAtoi(string s) {
int i = 0, positive = 1;
while (s[i] == ' ')
++i;
if (s[i] == '-') {
positive = -1;
++i;
} else if (s[i] == '+') {
++i;
}
long long res = 0;
while (s[i] >= '0' && s[i] <= '9') {
res *= 10;
res += int(s[i] - '0');
if (res > INT_MAX) {
return positive == 1 ? INT_MAX : INT_MIN;
}
++i;
}
return res * positive;
}
};
最小栈
class MinStack {
public:
MinStack() {
sta = {};
min = {};
}
void push(int val) {
if (min.empty() || min.front() >= val) {
min.push_front(val);
}
sta.push(val);
}
void pop() {
if (sta.top() == min.front()) {
sta.pop();
min.pop_front();
} else {
sta.pop();
}
}
int top() { return sta.top(); }
int getMin() { return min.front(); }
private:
stack<int> sta;
deque<int> min;
};
写过的题,再写一遍就要简洁很多。
|