zoukankan      html  css  js  c++  java
  • 72. Generate Parentheses && Valid Parentheses

    Generate 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。

    思路:可用于卡特兰数一类题目。

    void getParenthesis(vector<string> &vec, string s, int left, int right) {
        if(!right && !left) { vec.push_back(s); return; }
        if(left > 0)  
            getParenthesis(vec, s+"(", left-1, right);
        if(right > 0 && left < right)  
            getParenthesis(vec, s+")", left, right-1);
    }
    
    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> vec;
            getParenthesis(vec, string(), n, n);
            return vec;
        }
    };
    

    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.

    思路: 栈。对 S 的每个字符检查栈尾,若成对,则出栈,否则,入栈。

    class Solution {
    public:
        bool isValid(string s) {
            bool ans = true;
            char ch[6] = {'(', '{', '[', ']', '}', ')'};
            int hash[256] = {0};
            for(int i = 0; i < 6; ++i) hash[ch[i]] = i;
            string s2;
            for(size_t i = 0; i < s.size(); ++i) {
                if(s2 != "" && hash[s2.back()] + hash[s[i]] == 5) s2.pop_back();
                else s2.push_back(s[i]);
            }
            if(s2 != "") ans = false;
            return ans;
        }
    };
    
  • 相关阅读:
    使用JavaScriptSerializer进行JSON序列化
    清除浮动
    后台请求url数据
    设置Response中的ContentType
    javascript阻止事件冒泡
    如何启动Nunit的调试功能
    AjaxControlToolKit(整理)二···(全部源代码)
    DataRow对象数据绑定问题
    修改程序之感悟
    关于虚函数一个很好的解释
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3984575.html
Copyright © 2011-2022 走看看