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();
    }

  

 
posted @ 2017-03-30 19:37  会飞的胖子  阅读(107)  评论(0编辑  收藏  举报