20.有效的括号
题目如下
解题思路
这个涉及到括号的匹配,每次要匹配最近的括号,那么使用堆栈就不错!
Leetcode代码
class Solution {
public:
bool isValid(string s) {
stack<char> stack;
for(int i=0;i<s.length();i++){
if(stack.empty()){
stack.push(s[i]);
}else{
char t=stack.top();
if(t=='('&&s[i]==')'||t=='['&&s[i]==']'||t=='{'&&s[i]=='}'){
stack.pop();
}else{
stack.push(s[i]);
}
}
}
if(stack.empty()) return 1;
else return 0;
}
};
完整可运行代码
#include<iostream>
#include<stack>
#include<sstream>
#include<cstring>
using namespace std;
int main(){
stack<char> s;
stringstream ss;
string str;
getline(cin,str);
ss.str(str);
char temp;
while(ss>>temp){
if(s.empty()){
s.push(temp);
}else{
char t=s.top();
if(t=='('&&temp==')'||t=='['&&temp==']'||t=='{'&&temp=='}'){
s.pop();
}else{
s.push(temp);
}
}
if(ss=="") break;
}
if(s.empty()) cout<<"true"<<endl;
else cout<<"false"<<endl;
return 0;
}