zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses【栈】

    2017/3/30 19:26:58


    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.

     

    Subscribe to see which companies asked this question.


    版本1:O(n)   O(n)   简单题。多括号匹配问题,使用栈作为工具去匹配即可。
    注意事项:两个地方需要判断栈是否为空。一个是不够,一个是剩余。
    public boolean isValid(String s) {
            Stack<Character> ss = new Stack<Character>();
            for ( char c : s.toCharArray() )
            	if ( c == '(')
            		ss.push(')');
            	else if ( c == '[')
            		ss.push(']');
            	else if ( c == '{')
            		ss.push('}');
            	else if (ss.isEmpty() || ss.pop() != c )
            		return false;
    		return ss.empty();
        }
    

      

     
  • 相关阅读:
    c++ 中 pair 的 使用方法
    初窥c++11:lambda函数及其用法
    HDU2089-不要62
    算法训练 K好数
    点评删除和编辑
    事务
    SQL Function 自定义函数
    常用CSS实例
    分页显示数据
    开发教程指南
  • 原文地址:https://www.cnblogs.com/flyfatty/p/6648111.html
Copyright © 2011-2022 走看看