棧
基本概念
屬于數(shù)據結構的知識亚侠。LIFO胶逢,即last-in-fist-out厅瞎。
核心語法
包頭
#include<stack>
進棧,出棧初坠,讀出棧最上面的元素和簸,即 push pop top
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> myStack;
for (int i = 0; i < 5; i++)
{
myStack.push(i);
cout << "push " << i << endl;
}
int tmp;
while (!myStack.empty())
{
tmp = myStack.top();
cout << "pop " << tmp << endl;
cout << "size is " << myStack.size() << endl;
myStack.pop();
}
return 0;
}
奇淫巧技
將兩個棧的內容互換
A.swap(B) //A與B互換
例題
LeetCode-20
給定一個只包括 '(',')'碟刺,'{'锁保,'}','['半沽,']' 的字符串爽柒,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合者填。
左括號必須以正確的順序閉合浩村。
注意空字符串可被認為是有效字符串。
// test1.cpp : 此文件包含 "main" 函數(shù)占哟。程序執(zhí)行將在此處開始并結束心墅。
//
#include <iostream>
#include <string>
#include <stack>
using namespace std;
bool isValid(string s) {
int len = s.size();
if (len == 0)
{
return true;
}
if(len <= 1)
{
return false;
}
stack<char> myStack;
char c;
for (int i = 0; i < len; i++)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
{
myStack.push(s[i]);
}
else
{
if (myStack.empty())
{
return false;
}
c = myStack.top();
if (c == '}' || c == ']' || c == ')')
{
return false;
}
if ((s[i] == ')' && c == '(') || (s[i] == ']' && c == '[') || (s[i] == '}' && c == '{'))
{
myStack.pop();
}
else
{
return false;
}
}
}
if (myStack.empty())
{
return true;
}
else
return false;
};
int main()
{
string str = "((";
if (isValid(str))
cout << str << "is right";
else
cout << str << "is wrong";
return 0;
}
其中采用map的方式進行匹配確定,可以簡化算法
class Solution {
public:
bool isValid(string s) {
unordered_map<char,int> m{{'(',1},{'[',2},{'{',3},
{')',4},{']',5},{'}',6}};
stack<char> st;
bool istrue=true;
for(char c:s){
int flag=m[c];
if(flag>=1&&flag<=3) st.push(c);
else if(!st.empty()&&m[st.top()]==flag-3) st.pop();
else {istrue=false;break;}
}
if(!st.empty()) istrue=false;
return istrue;
}
};