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. 

可以使用Stack,扫描一遍String即可,当前字符为’(’,'[','{' 压入栈中,当遇到的字符为')',']','}'时弹出栈顶元素判断是否与其匹配,如果不匹配或stack为空返回false.

当扫描完String后如果Stack的元素非空返回false,否则返回true.

 1 public class Solution {
 2     public boolean isValidParentheses(String s) {
 3         Stack<Character> stack = new Stack<Character>();
 4         for (Character c : s.toCharArray()) {
 5         if ("({[".contains(String.valueOf(c))) {
 6                 stack.push(c);
 7             } else {
 8                if (!stack.isEmpty() && is_valid(stack.peek(), c)) {
 9                    stack.pop();
10                } else {
11                    return false;
12                }
13            }
14        }
15        return stack.isEmpty();
16     }
17 
18     private boolean is_valid(char c1, char c2) {
19         return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}')
20             || (c1 == '[' && c2 == ']');
21     }
22 }

 

posted @ 2016-03-23 11:33  YuriFLAG  阅读(175)  评论(0)    收藏  举报