zoukankan      html  css  js  c++  java
  • Lintcode423-Valid Parentheses-Easy

    423. 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.

    Example

    Example 1:

    Input: "([)]"
    Output: False
    

    Example 2:

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

    Challenge

    Use O(n) time, n is the number of parentheses.

    思路:

    遍历String,左向括号入栈,当遇到右向括号时,(如果栈此时为空,则返回false)pop一个出来,并与右向括号匹配,看是否为一对。如果不是一对,则返回false。

    遍历完整个数组,记得再检查栈是否为空,即左向括号数量=右向括号数量。所以  return (stack.isEmpty()); 

    代码:

    for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '(' || s.charAt(i) == '['||s.charAt(i) == '{')
                    stack.push(s.charAt(i));
                else{
                    if (stack.isEmpty()) 
                        return false;
                    char pop = stack.pop();
                    if (s.charAt(i) == ')' && (pop == '[' || pop == '{'))
                        return false;
                    if (s.charAt(i) == ']' && (pop == '(' || pop == '{'))
                        return false;
                    if (s.charAt(i) == '}' && (pop == '(' || pop == '['))
                        return false;
                }    
            }return stack.isEmpty();
        }
  • 相关阅读:
    非常抱歉,全站内容审核中...
    jS代码总结(2)
    timestamp(数据库中的数据类型)
    jS代码总结(1)
    TextWriterTraceListener 和设计时属性支持文件xmta
    validating和validated的区别
    IoC和控制反转
    wince BindingSource
    简单网络传递加密数据
    C#不对称加密
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10649934.html
Copyright © 2011-2022 走看看