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();
        }
  • 相关阅读:
    shell入门-cut命令
    shell入门-特殊符号
    shell入门-系统和用户的配置文件
    shell入门-变量
    shell入门-shell特性
    linux命令-yum工具详解
    linux命令-rpm查询包
    linux命令-rpm安装和卸载
    math 数学模块
    random 随机模块
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10649934.html
Copyright © 2011-2022 走看看