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();
        }
  • 相关阅读:
    SEO优化范列20120215
    IIS中的上传目录权限设置问题
    c# webservice接口 输出xml
    360浏览器用window.open的话,session会丢失
    iis网站安全设置
    SEO优化20120215
    IIS6.0安全设置方法 .
    优化20120215
    WIN2003的安全设置
    webservice 生成dll的方法
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10649934.html
Copyright © 2011-2022 走看看