题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例1
输入:
“()”
输出:
true
示例2
输入:
“()[]{}”
输出:
true
示例3
输入:
“(]”
输出:
false
示例4
输入:
“([)]”
输出:
false
示例5
输入:
“{[]}”
输出:
true
解法
- 把字符押入堆栈,遇到’)’ 、’]’、’}'时取出前一个字符判断是否有效
- 注意堆栈为空的情况
- 注意字符串为空的时候
代码
#include <stdio.h>
#include <stack>
#include <cstring>
#include <iostream>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> sta;
if(s.size()==0){return true;}
sta.push(s[0]);
for(int i = 1;i < s.size();i++){
char ch = s[i];
if(s[i]==')'){
if(sta.empty()){return 0;}
char tmp = sta.top();
sta.pop();
if(tmp !='(')
{return 0;}
}
else if(s[i]==']'){
if(sta.empty()){return 0;}
char tmp = sta.top();
sta.pop();
if(tmp !='[')
{return 0;}
}
else if(s[i]=='}'){
if(sta.empty()){return 0;}
char tmp = sta.top();
sta.pop();
if(tmp !='{')
{return 0;}
}
else{
sta.push(ch);
}
}
return sta.empty();
}
};
int main()
{
string str;
str = "[)";
Solution s;
cout<<s.isValid(str);
return 0;
}
今天也是爱zz的一天哦!