给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法:栈
若遇到前括号则入栈,若遇到后括号则判断是否匹配,若匹配则前括号出栈,若不匹配则直接返回false,时间复杂度和空间复杂度都是O(n)。
class Solution {
public:
bool isValid(string s) {
stack<char> store;
int size=s.size();
if(size==0){
return true;
}
map<char,char> match={{')','('},{']','['},{'}','{'}};
for(int i=0;i<size;i++){
if(s[i]=='('||s[i]=='['||s[i]=='{') store.push(s[i]);
else {
if(store.empty()) return false;
if (store.top()!=match[s[i]]){
return false;
}else{
store.pop();
}
}
}
if (store.empty()) return true;
else return false;
}
};