• 【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 == '}');
        }
    };


  • 相关阅读:
    python-TCP传输模型
    python-锁机制
    python-生产者消费者模式
    python-Lock锁线程同步和互斥
    python-Event事件线程同步和互斥
    python-thread封装类创建线程
    python-fifo管道文件通信
    python-thread多线程
    Sublime一些设置
    gdb的user-define command
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3053809.html
Copyright © 2020-2023  润新知