|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目描述:
- 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
- 有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 注意空字符串可被认为是有效字符串。
- 示例 1:
- 输入: "()"
- 输出: true
- 示例 2:
- 输入: "()[]{}"
- 输出: true
- 示例 3:
- 输入: "(]"
- 输出: false
- 示例 4:
- 输入: "([)]"
- 输出: false
- 示例 5:
- 输入: "{[]}"
- 输出: true
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/valid-parentheses
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- class Solution {
- public:
- bool isValid(string s) {
- stack<char> store;
- int count1 = 0, count2 = 0, count3 = 0;
- for(auto cha : s){
- if(cha == '('){
- count1 ++;
- store.push('(');
- }else if(cha == ')'){
- count1 --;
- if(count1 < 0) return false;
- if(store.top() == '('){
- store.pop();
- }else if(store.top() != '('){
- return false;
- }
- }else if(cha == '['){
- count2 ++;
- store.push('[');
- }else if(cha == ']'){
- count2 --;
- if(count2 < 0) return false;
- if(store.top() == '['){
- store.pop();
- }else if(store.top() != '['){
- return false;
- }
-
- }else if(cha == '{'){
- count3 ++;
- store.push('{');
- }else if(cha == '}'){
- count3 --;
- if(count3 < 0) return false;
- if(store.top() == '{'){
- store.pop();
- }else if(store.top() != '{'){
- return false;
- }
- }
- }
- return count1 == 0 && count2 == 0 && count3 == 0;
- }
- };
复制代码 |
|