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;
    }

     
  • 相关阅读:
    JavaScript: RegExp + replace
    JavaScript:布局
    DOM和BOM区别
    正则表达式
    a report about the history of pragrem
    web第6次作业position
    web api
    DOM Event:事件流动(Event Flow)
    FOR衍生对象
    前端的发展
  • 原文地址:https://www.cnblogs.com/ganeveryday/p/4903679.html
Copyright © 2011-2022 走看看