首页 > 其他 > 详细

【LeetCode从零单排】No20.ValidParentheses

时间:2015-02-09 12:52:24      阅读:131      评论:0      收藏:0      [点我收藏+]

题目

       

     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。

代码

public class Solution {
    public boolean isValid(String s) {
         if(s.length()==0) return true;
        int len=s.length();
        char[] symbolFirst={‘(‘,‘{‘,‘[‘};
        char[] symbolSecond={‘)‘,‘}‘,‘]‘};
        char strChar[]=s.toCharArray();     
        Stack sym=new Stack();
        for(int i=0;i<len;i++){
        	  for(int j=0;j<symbolFirst.length;j++){
        		  if(strChar[i]==symbolFirst[j]){
        		      if(len==1){
        				  return false;
        				  }
        			  sym.push(strChar[i]);
        		  }       		  
        	  }
        	  for(int k=0;k<symbolSecond.length;k++){
        		  if(strChar[i]==symbolSecond[k]){
        			  if(sym.isEmpty()){
        				  return false;
        			  }
        			  else{
        				  if(!sym.peek().equals(symbolFirst[k])){
        					  
        					  return false;   
        			      }
        				  else{
        					  sym.pop();
        				  }
        		  }
        	  }}}
        
      if(sym.isEmpty())
        {
        	return true;
        }
        else{
        	return false;
        }   
    }
}


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/


【LeetCode从零单排】No20.ValidParentheses

原文:http://blog.csdn.net/buptgshengod/article/details/43668801

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!