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


  • 相关阅读:
    分享一下我珍藏的各种资料。
    JEditorPane中html文档中文乱码解决
    ubuntu恢复rm -rf误删文件
    MBR与分区表备份与恢复
    ubuntu tab命令补全失效
    selinux理解1-selinux介绍
    Mac-Xcode统计整个项目代码行数
    Mac清理空间-Xcode-删除相关文件
    # iOS开发
    Charles问题总结-最新版4.5.6
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3053809.html
Copyright © 2011-2022 走看看