zoukankan      html  css  js  c++  java
  • 【leetcode】Valid Parentheses

    Question :  

    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.

    Anwser 1 :    Stack

    class Solution {
    public:
        bool isValid(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            stack<char> st;
            for(int i = 0; i < s.size(); i++)
            {
                if(s[i] == '(' || s[i] == '{' || s[i] == '['){
                    st.push(s[i]);
                }
                   
                if(s[i] == ')')
                {
                    if(st.empty() || st.top() != '(')
                       return false;
                    st.pop();
                }
                if(s[i] == '}')
                {
                    if(st.empty() || st.top() != '{')
                       return false;
                    st.pop();
                }
                if(s[i] == ']')
                {
                    if(st.empty() || st.top() != '[')
                       return false;
                    st.pop();
                }            
            }
            if(st.empty() == 0)
               return false;
               
            return true;
        }
    };


    Anwser 2 :   

    class Solution {
    public:
        bool isValid(string s) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            stack<char> st;
            for (int i = 0; i < s.size(); i++) {
                char c = s[i];
                if (isLeft(c)) {    // push
                    st.push(c);
                } else {
                    if (st.empty()) {
                        return false;
                    }
                    char d = st.top();      // pop
                    st.pop();
                    if (!match(d,  c)) {
                        return false;
                    }
                }
            }
     
            if (st.empty()) {
                return true;
            }
            else {
                return false;
            }
        }
     
        bool isLeft(char c) {
            return c == '{' || c == '[' || c == '(';
        }
        
        bool match(char c, char d) {
            return (c == '(' && d == ')') || (c == '[' && d == ']') || (c == '{' && d == '}');
        }
    };


  • 相关阅读:
    结构型模式のBridge桥梁模式
    创建型模式のBuilder建造者模式
    设计模式的一点思考
    创建型模式のAbstractFactory抽象工厂模式
    初试phoenix
    内网搭建git server
    nsq 学习(三)nsqlookupd
    nsq 学习(二)简单使用
    nsq 学习(一)源码安装nsq
    go学习实践-protobuf
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3053809.html
Copyright © 2011-2022 走看看