• 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();
        }
  • 相关阅读:
    Session
    python内存优化机制中的小秘密
    跨域请求
    Cookie
    json
    Python深浅拷贝辨析
    Django form组件相关
    Python 中的 if __name__ == '__main__'
    online_judge_1108
    online_judge_1107
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10649934.html
Copyright © 2020-2023  润新知