class Solution {
public:
/**
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
int cd=s.size();
stack<char>st;
for(int i=0;i<cd;i++){
if(s[i]=='('||s[i]=='['||s[i]=='{')
st.push(s[i]);
else{
if(s[i]==')'&&(st.empty()||st.top()!='('))
return false;
if(s[i]==']'&&(st.empty()||st.top()!='['))
return false;
if(s[i]=='}'&&(st.empty()||st.top()!='{'))
return false;
st.pop();
}
}
if(!st.empty())
return false;
else
return true;
}
};
class Solution {
public:
/**
*
* @param s string字符串
* @return int整型
*/
int longestValidParentheses(string s) {
// write code here
int cd=s.size();
if(cd==0)
return 0;
int mx=0;
stack<int>st;
for(int i=0;i<cd;i++){
if(s[i]==')'&&!st.empty()&&s[st.top()]=='('){
st.pop();
if(st.empty())
mx=max(mx,i+1);
else
mx=max(mx,i-st.top());
}
else
st.push(i);
}
return mx;
}
};
class Solution {
public:
/**
* return a array which include all ans for op3
* @param op int整型vector<vector<>> operator
* @return int整型vector
*/
vector<int> getMinStack(vector<vector<int> >& op) {
// write code here
stack<int> S;
stack<int> minS;
vector<int> ans;
for(int i=0;i<op.size();i++){
if(op[i][0]==1)//插入
{
S.push(op[i][1]);
if(minS.empty()||op[i][1]<=minS.top())
minS.push(op[i][1]);
}
else if(op[i][0]==2)//出栈
{
int t=S.top();
S.pop();
if(!minS.empty()&&t==minS.top())
minS.pop();
}
else if(op[i][0]==3)//获得栈中最小值
{
ans.push_back(minS.top());
}
}
return ans;
}
};
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
int t=stack2.top();
stack2.pop();
return t;
}
private:
stack<int> stack1;
stack<int> stack2;
};
class Solution {
public:
/**
* lru design
* @param operators int整型vector<vector<>> the ops
* @param k int整型 the k
* @return int整型vector
*/
struct node{
int key;
int value;
node* pre=NULL;
node* next=NULL;
};
map<int,node*>M;
node* front;
node* end;
void Delete(node* now){
node* PRE=now->pre;
node* NEXT=now->next;
PRE->next=NEXT;
NEXT->pre=PRE;
}
void Push_back(node* now){
node* PRE=end->pre;
node* NEXT=end;
PRE->next=now;
now->pre=PRE;
now->next=end;
end->pre=now;
}
vector<int> LRU(vector<vector<int> >& operators, int k) {
// write code here
int ct=0;
vector<int>ans;
front=new node;
end=new node;
front->next=end;
end->pre=front;
for(int i=0;i<operators.size();i++){
if(operators[i][0]==1)//set操作
{
if(ct<k)
ct++;
else//删除链表首位元素
{
node* first=front->next;
Delete(first);
M.erase(first->key);
delete first;
}
//插入当前的元素
node* now=new node;
now->key=operators[i][1];
now->value=operators[i][2];
M[operators[i][1]]=now;
Push_back(now);
}
else if(operators[i][0]==2)//get操作
{
//看一下有没有对应的key
int Key=(operators[i][1]);
if(M.find(Key)==M.end())//
ans.push_back(-1);
else{
//查一下对应的value,放入
node* now=M[operators[i][1]];
ans.push_back(now->value);
Delete(now);
Push_back(now);
//把当前结点移到链表的末尾
}
}
}
return ans;
}
};