zoukankan      html  css  js  c++  java
  • [LeetCode]35. 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.

    解法:很简单的题目,使用stack即可。遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回false。

    class Solution {
    public:
        bool isValid(string s) {
            int ss = s.size();
            if(ss % 2 != 0) return false;
            stack<char> par;
            for (int i = 0; i < ss; i++)
            {
                switch (s[i])
                {
                case '(':
                case '[':
                case '{':
                    par.push(s[i]); break;
                case ')':
                    if (par.empty() || par.top() != '(') return false;
                    par.pop();
                    break;
                case ']':
                    if (par.empty() || par.top() != '[') return false;
                    par.pop();
                    break;
                case '}':
                    if (par.empty() || par.top() != '{') return false;
                    par.pop();
                    break;
                default:
                    return false;
                }
            }
            return par.empty();
        }
    };
  • 相关阅读:
    mysql 创建++删除 数据表
    mac 配置apache
    mac 安装mysql
    mysql 创建++删除 数据库
    配置默认编码为utf8
    mysql 添加用户
    mysql 查看库结构---查看表结构
    centos7
    centOS 7 安装mysql
    修改字符集
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4903837.html
Copyright © 2011-2022 走看看