1.题目如下:
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
提示:
1 <= s.length <= 104
s 仅由括号 ‘()[]{}’ 组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-parentheses
2.代码如下:
class Solution {
public:
bool isValid(string s) {
int length=s.length();
stack<char> a=*new stack<char>();
if(length%2!=0){
return false;
}
//通过栈来实现
else{
for(int i=0;i<length;i++){
if(a.empty()!=1){
//取顶部元素
char temp=a.top();
a.push(s[i]);
//如果配对,直接弹出
if(isNo(temp,a.top())){
a.pop();
a.pop();
}
}
else{
//不配对就压入栈等待
a.push(s[i]);
}
}
//全部元素压进去,如果不能完全抵消,则代表不成对,返回false
if(a.empty()!=1){
return false;
}
return true;
}
}
//判断是否是成对的括号
bool isNo(char a,char b){
char temp[6] ={'(',')','{','}','[',']'};
int pos=0;
for(int i=0;i<6;i++){
if(a==temp[i]){
pos=i;
}
}
if(pos%2==0){
if(b==temp[pos+1]){
return true;
}
else{
return false;
}
}
return false;
}
};