73. Valid Parentheses

来源:互联网 发布:只有淘宝网页打不开 编辑:程序博客网 时间:2024/06/06 02:25

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.

分析: 判断给定的字符串中的括号是否合法。采用栈的思想做。 
   遇到左边括号则入栈;
   遇到右边括号则首先判断栈是否为空,为空则返回false,否则与弹出的栈顶元素比较,如果配对则继续,否则返回false
   最后判断栈是否为空,空则返回true,否则返回false。
 

/** * 判断给定的字符串中的括号是否合法。 * 采用栈的思想做。  * 遇到左边括号则入栈; * 遇到右边括号则首先判断栈是否为空,为空则返回false,否则与弹出的栈顶元素比较,如果配对则继续,否则返回false。 * 最后判断栈是否为空,空则返回true,否则返回false。 */ public boolean isValid(String s) { Stack stack = new Stack(); int len = s.length(); for(int i = 0;i<len;i++){ char c = s.charAt(i); char top; switch(c){ case '(': case '[': case '{':stack.push(c);break;//遇到左边括号则入栈。 case ')': if(stack.isEmpty()){ return false; } top = (char) stack.pop(); if(top=='('){ break;//配对成功则继续 }else{ return false; } case ']': if(stack.isEmpty()){ return false; } top = (char) stack.pop(); if(top=='['){ break;//配对成功则继续 }else{ return false; } case '}':  if(stack.isEmpty()){ return false; } top = (char) stack.pop(); if(top=='{'){ break;//配对成功则继续 }else{ return false; } } }//end for /*最后判断栈是否为空,空则返回true,否则返回false*/ return stack.isEmpty(); }


0 0