zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses

    问题描述:

    Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

    Input: "()[]{}"
    Output: true
    

    Example 3:

    Input: "(]"
    Output: false
    

    Example 4:

    Input: "([)]"
    Output: false
    

    Example 5:

    Input: "{[]}"
    Output: true

    解题思路:

    1.如果要是一个合法的括号匹配,那么字符串长度必须为偶数,若为奇数,则显然不可能完成匹配

    2.空字符串为合法匹配。

    接下来可以对每一个字符进行检查:

      如果是左括号,压入栈中

      如果是右括号,检查栈是否为空,若为空说明右括号多余,不匹配。

             若不为空,则检查栈顶是否是可以与之匹配的左括号,不是也不匹配,是的话要弹出栈顶元素

    遍历完字符串后,我们得到的结论是:所有右括号都得到了合法的匹配,但是左括号不确定,所以我们要检查栈是否为空来判断是否有多余的左括号。

    代码:

    class Solution {
    public:
        bool isValid(string s) {
            if(s.size() % 2 == 1)
                return false;
            stack<char> stk;
            for(int i = 0; i < s.size(); i++){
                if(s[i] == '(' || s[i] == '[' || s[i] =='{')
                    stk.push(s[i]);
                else{
                    if(stk.empty()) return false;
                    char c = stk.top();
                    if(s[i] == ')' && c != '(') return false;
                    if(s[i] == ']' && c != '[') return false;
                    if(s[i] == '}' && c != '{') return false;
                    stk.pop();
                }
            }
            if(!stk.empty()) return false;
            return true;
        }
    };
  • 相关阅读:
    WM_COMMAND 和 WM_NOTIFY 的区别
    C 游戏所要看的书
    Source Insight中文字体设置
    在 windows7 中使用 vs2003 时,“在文件中查找”导致无响应的问题
    解决VS2008 调试启动特别慢
    c++ 浅谈 new 的使用
    Access界面基础操作
    与孩子一起学编程12章
    YT工作日志-0911
    两种方式遍历二叉树--递归方式和非递归方式
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9297461.html
Copyright © 2011-2022 走看看