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.
思路:利用栈,当遇到左括号就进栈,当遇到右括号就与栈顶元素进行匹配,如果不匹配就返回falsse。
AC:
public class Solution { public boolean isValid(String s) { if(s.length() == 0 || s.length() == 1){ return false; } Stack<Character> stack = new Stack<Character>(); for(int i=0;i<s.length();i++){ char temp = s.charAt(i); if(temp == '(' || temp == '{' || temp == '['){ stack.push(temp); }else{ switch(temp){ case ')': if(stack.isEmpty() || stack.pop() != '('){ return false; } break; case ']' : if(stack.isEmpty() || stack.pop() != '['){ return false; } break; case '}' : if(stack.isEmpty() || stack.pop() != '{'){ return false; } break; default : break; } } } if(stack.size() == 0) return true; else return false; } }