LeetCode日记2020.2.6
文章目录
栈强化训练@_@
103 二叉树的锯齿形层次遍历(mid)
双栈实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
stack<TreeNode*> ls, rs;
if(root != NULL)
{
res.push_back(vector<int>{root->val});
ls.push(root);
}
while(!ls.empty() || !rs.empty())
{
res.push_back(vector<int>());
auto& bac = res.back();
while(!ls.empty())
{
auto t = ls.top();
ls.pop();
if(t->right != NULL)
{
bac.push_back(t->right->val);
rs.push(t->right);
}
if(t->left != NULL)
{
bac.push_back(t->left->val);
rs.push(t->left);
}
}
if(!bac.empty())
res.push_back(vector<int>());
auto& bac2 = res.back();
while(!rs.empty())
{
auto t = rs.top();
rs.pop();
if(t->left != NULL)
{
bac2.push_back(t->left->val);
ls.push(t->left);
}
if(t->right != NULL)
{
bac2.push_back(t->right->val);
ls.push(t->right);
}
}
if(bac2.empty())
res.erase(res.end());
}
return res;
}
};
503 下一个更大元素2(mid)
单调递减栈
class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
stack<int> s;
vector<int> res(nums.size(), -1);
int cnt = 0, mod = nums.size(), total = 2 * nums.size();
while(cnt < total)
{
int idx = cnt%mod;
while(!s.empty() && nums[idx] > nums[s.top()])
{
if(res[s.top()] == -1)
res[s.top()] = nums[idx];
s.pop();
}
s.push(idx);
++cnt;
}
return res;
}
};
1209 删除字符串中的所有相邻重复项(mid)
class Solution {
public:
string removeDuplicates(string s, int k) {
using KV = pair<int, char>;
vector<KV> st;
for(const auto& c: s)
{
if(st.empty() || st.back().second != c)
st.push_back(KV(1, c));
else
{
if(++st.back().first == k)
st.pop_back();
}
}
string res;
for(const auto& c: st)
{
res.append(c.first, c.second);
}
return res;
}
};
1190 反转每对括号间的子串(mid)
class Solution {
public:
string reverseParentheses(string s) {
stack<int> st;
string res;
for(int i=0; i<s.size(); ++i)
{
char c = s[i];
if(c == '(')
st.push(res.size());
else if(c == ')')
{
if(!st.empty())
{
reverse(res.begin()+st.top(), res.end());
st.pop();
}
}
else
res.append(1, c);
}
return res;
}
};
150 逆波兰表达式求值(mid)
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for(const auto& c: tokens)
{
if(!s.empty() && c.size() == 1 && !isdigit(c[0]))
{
int rh = s.top();
s.pop();
int lh = s.top();
s.pop();
if(c == "+")
s.push(lh + rh);
else if(c == "-")
s.push(lh - rh);
else if(c == "*")
s.push(lh * rh);
else
s.push(lh / rh);
}
else
s.push(stoi(c));
}
return s.top();
}
};