【Leetcode长征系列】Valid Parentheses

原题:

Given a string containing just the characters '(', ')','{','}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but"(]" and"([)]" are not.

思路:

首先string长度必须为偶数,否则报错。其次每一对括号必须在一起,否则报错。

代码:

class Solution {
public:
    bool isValid(string s) {
        if (s.size()%2!=0) return false;
        
        for (int j = 0; j<s.size()-1; j+=2){
            if(s[j]=='(') {
                if(s[j+1]==')') continue;
                else return false;
            }
            if(s[j]=='[') {
                if(s[j+1]==']') continue;
                else return false;
            }
            if(s[j]=='{') {
                if(s[j+1]=='}') continue;
                else return false;
            }
        }
    }
};
报错了…

=================================================================================================================================

之前读题有问题,后来再理解一遍后觉得,还是需要一个堆栈的。重写代码如下:

class Solution {
public:
    bool isValid(string s) {
        stack<char> p;
        char c;
        
        for(int i = 0; i<s.size(); i++){
            if(s[i]=='(' || s[i]=='[' || s[i]=='{')     p.push(s[i]);
            else{
                if(p.empty()) return false;
                c = p.top();
                if((s[i]==')' && c=='(')||(s[i]==']' && c=='[')||(s[i]=='}' && c=='{'))      p.pop();
                else return false;
            }
        }
        if (!p.empty()) return false;
        return true;
    }
};
但还是卡在一样的地方了,WA…

================================================================================================================================

class Solution {
public:
    bool isValid(string s) {
        stack<char> p;
        
        for(int i = 0; i<s.size(); i++){
            if(s[i]=='(' || s[i]=='[' || s[i]=='{')     p.push(s[i]);
            else{
                if(p.empty()) return false;
                if((s[i]==')' && p.top()=='(')||(s[i]==']' && p.top()=='[')||(s[i]=='}' && p.top()=='{'))      p.pop();
                else return false;
            }
        }
        if (!p.empty()) return false;
        return true;
    }
};
AC了。


你真得没有在逗我么- -#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值