算法-栈和队列:匹配括号
一个字符串只要有左括号"("、"{"、"[",就会有")"、"}"、"]"。字符串只包含以上字符,判断字符串是否合法。
思路解析:括号匹配是用栈解决的经典问题。依次遍历字符串,将左括号依次进栈,当出现右括号时,与栈头元素进行匹配,匹配会出现以下几种不匹配的情况:
- 右括号和栈头左括号不匹配;
- 右括号匹配时栈已经空了;
- 遍历结束了,但栈没空。
小技巧:在进行左括号进栈操作时,直接将相应的右括号推入栈,这样匹配的时候判断是否相等就行。
#include <iostream>
#include <stack>
using namespace std;
bool isValid(string s){
stack<int> st;
for(int i = 0; i < s.size(); i++){
if('(' == s[i]){
st.push(')');
}
else if('[' == s[i]){
st.push(']');
}
else if('{' == s[i]){
st.push('}');
}
else{ //右括号
if(s[i]!=st.top() || st.empty()) { //不匹配情况1 2
return false;
}
cout<<"栈内容:"<<st.top()<<" "<<s[i]<<endl;
st.pop();
}
}
return st.empty();//不匹配情况3
}
int main(){
string s;
while (cin>>s) {
cout<<isValid(s)<<endl;
}
return 0;
}
注意:栈存入的是字符相应的int值,也可以直接与字符进行比较,因为比较时都会将字符转为相应int值。