#1、描述
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#2、解题思路
1、用栈存起来左边的符号,判断后来的能不能匹配,
2、用unordered_map <char,int> m{ { '(' , -1} , { ')' , 1} };构造字符和用来判断的数字的关系
3、for( char c : s) // 用来遍历string 字符串中的所有元素
#3、notes:
1、判空不能省
#4、code
class Solution {
public:
bool isValid(string s) {
stack<char>st;
unordered_map<char,int> m {{'(',-1},{'[',-2},{'{',-3},{')',1},{']',2},{'}',3}};
bool istrue=true;
for(char c:s)
{
int flag=m[c];
if(flag<0) st.push(c);
else if(!st.empty() && flag+m[st.top()]==0) st.pop(); //判空不能省
else
{
istrue=false;
break;
}
}
if(!st.empty())
istrue=false;
return istrue;
}
};