题目描述:
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.
思路:
判定括号是否完整。使用堆栈的方法,如果是左括号,则push入栈,如果是右括号,则将栈内元素挨个pop出来,与之比较。直到最后一个匹配完成,则为valid。
Stack<参数可以是String或者Character>
堆栈的操作是,peek和pop都是返回栈顶元素,但peek不会移除栈顶的值,pop会删除栈顶的值
1 public class Solution20 { 2 public boolean isValid(String s) { 3 Stack<Character> stack = new Stack<Character>(); 4 for(int i = 0; i < s.length();i++){ 5 if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{'){ 6 stack.push(s.charAt(i)); 7 }else{ 8 if(stack.isEmpty()){return false;} 9 if((s.charAt(i)==')'&&stack.peek()=='(')|| 10 (s.charAt(i)==']'&&stack.peek()=='[')|| 11 (s.charAt(i)=='}'&&stack.peek()=='{')){ 12 stack.pop(); 13 }else { 14 return false; 15 } 16 } 17 } 18 if (stack.isEmpty()) { 19 return true; 20 } 21 return false; 22 } 23 public static void main(String[] args) { 24 // TODO Auto-generated method stub 25 Solution20 solution20 = new Solution20(); 26 String s = "{{{(])}}}"; 27 System.out.println(solution20.isValid(s)); 28 } 29 30 }