标签:
标题: | Valid Parentheses |
通过率: | 27.7% |
难度: | 简单 |
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.
本题是传统的符号匹配题用一个栈来模拟就行了。遇见(,{,[全部进栈,遇到),},]进行弹栈比较,如果不是() [] {}则返回错误,直接看代码:
1 public class Solution { 2 public boolean isValid(String s) { 3 int len=s.length(); 4 Stack<Character> stack = new Stack<Character>(); 5 for(int i=0;i<len;i++){ 6 char tmp=s.charAt(i); 7 if(tmp==‘(‘||tmp==‘{‘||tmp==‘[‘){ 8 stack.push(tmp); 9 } 10 if(tmp==‘)‘||tmp==‘}‘||tmp==‘]‘){ 11 if(stack.empty())return false; 12 char ctr=stack.pop(); 13 if(tmp==‘)‘&&ctr==‘(‘) continue; 14 if(tmp==‘]‘&&ctr==‘[‘) continue; 15 if(tmp==‘}‘&&ctr==‘{‘) continue; 16 else return false; 17 } 18 } 19 if(stack.empty())return true; 20 else{ 21 return false; 22 } 23 } 24 }
标签:
原文地址:http://www.cnblogs.com/pkuYang/p/4231595.html