20. Valid Parentheses
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
if(s.size() % 2 == 1)
return false;
for(int i=0; i<s.size(); i++){
if(s[i] == '('){
stk.push(')');
}else if(s[i] == '{'){
stk.push('}');
}else if(s[i] == '['){
stk.push(']');
}else{
if(stk.empty() || s[i] != stk.top()){
return false;
}
stk.pop();
}
}
return stk.empty();
}
};
有两种特殊情况,第一种,一出现就是右括号(代码中的体现是判断的时候要写stk.empty(), 不能只写不等)第二种是左括号多出来了(代码体现在最后return stk.empty)
1047. Remove All Adjacent Duplicates In String
class Solution {
public:
string removeDuplicates(string s) {
stack<char> stk;
for(int i=0; i<s.size(); i++){
if(!stk.empty() && s[i] == stk.top()){
stk.pop();
}else{
stk.push(s[i]);
}
}
string res;
while(!stk.empty()){
res.push_back(stk.top());
stk.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
150. Evaluate Reverse Polish Notation
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for(int i=0; i<tokens.size(); i++){
int num1=0, num2=0;
int res = 0;
if(tokens[i] == "+"){
num1 = stk.top();
stk.pop();
num2 = stk.top();
stk.pop();
res = num1+num2;
stk.push(res);
}else if(tokens[i] == "*"){
num1 = stk.top();
stk.pop();
num2 = stk.top();
stk.pop();
res = num1*num2;
stk.push(res);
}else if(tokens[i] == "-"){
num1 = stk.top();
stk.pop();
num2 = stk.top();
stk.pop();
res = num2 - num1;
stk.push(res);
}else if(tokens[i] == "/"){
num1 = stk.top();
stk.pop();
num2 = stk.top();
stk.pop();
res = num2 / num1;
stk.push(res);
}else{
stk.push(stoi(tokens[i]));
}
}
return stk.top();
}
};
239. Sliding Window Maximum
class Solution {
private:
class MyQueue{
public:
deque<int> que;
void pop(int val){
if(!que.empty() && val == que.front()){
que.pop_front();
}
}
void push(int val){
while(!que.empty() && val > que.back()){
que.pop_back();
}
que.push_back(val);
}
int front(){
return que.front();
}
};
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
MyQueue que;
vector<int> res;
for(int i=0; i<k; i++){
que.push(nums[i]);
}
res.push_back(que.front());
for(int i=k; i<nums.size(); i++){
que.pop(nums[i-k]);
que.push(nums[i]);
res.push_back(que.front());
}
return res;
}
};
347. Top K Frequent Elements
class Solution {
public:
class mycomparison{
public:
bool operator()(const pair<int, int>& lhs, const pair<int, int>& rhs){
return lhs.second > rhs.second;
}
};
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> map;
for(int i=0; i<nums.size(); i++){
map[nums[i]]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, mycomparison> pri_que;
for(unordered_map<int, int> :: iterator it = map.begin(); it != map.end(); it++){
pri_que.push(*it);
if(pri_que.size() > k){
pri_que.pop();
}
}
vector<int> res(k);
for(int i=k-1; i>=0; i--){
res[i] = pri_que.top().first;
pri_que.pop();
}
return res;
}
};
这是小顶堆,小的先被弹出去(这道题只是看懂了)