zoukankan      html  css  js  c++  java
  • leetcode_20_Valid Parentheses (easy)

    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.

    解题:
    一看题目,就想到应该用栈的思想来做


    #include <iostream>
    using namespace std;

    class Solution {
    public:
        bool isValid(string s) {
            char a[100];
            for(int i=0;i<100;i++){
                a[i] = '0';
            }
            int end=0;
            for(int i = 0;i<s.size();i++){
                if(a[end]=='('){
                    if(s.at(i)==')'){
                        a[end] = '0';
                        if(end>0)
                         end--;
                    }else if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
                        a[++end]=s.at(i);
                    }else{
                        return false;
                    }
                }else if(a[end]=='['){
                    if(s.at(i)==']'){
                        a[end] = '0';
                        if(end>0)
                         end--;
                    }else if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
                        a[++end]=s.at(i);
                    }else{
                        return false;
                    }
                }else if(a[end]=='{'){
                    if(s.at(i)=='}'){
                        a[end] = '0';
                        if(end>0)
                          end--;
                    }else if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
                        a[++end]=s.at(i);
                    }else{
                        return false;
                    }
                }else{
                    if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
                       a[end] = s.at(i);
                    }else{
                        return false;
                    }
                }

            }
            if(a[end]!='0'){
                return false;
            }
            return true;
        }
    };

    int main(int argc, const char * argv[]) {
        Solution a;
        cout<<a.isValid("{{})")<<endl;
        return 0;
    }

     
  • 相关阅读:
    老王讲架构:负载均衡
    支付宝系统架构内部剖析
    Effective Java 第三版——61. 基本类型优于装箱的基本类型
    Effective Java 第三版——60. 需要精确的结果时避免使用float和double类型
    Effective Java 第三版——59. 熟悉并使用Java类库
    Effective Java 第三版——58. for-each循环优于传统for循环
    Effective Java 第三版——57. 最小化局部变量的作用域
    Effective Java 第三版——56. 为所有已公开的API元素编写文档注释
    Effective Java 第三版——55. 明智而审慎地返回Optional
    Effective Java 第三版——54. 返回空的数组或集合不要返回null
  • 原文地址:https://www.cnblogs.com/ganeveryday/p/4903679.html
Copyright © 2011-2022 走看看