LeetCode - Valid Parentheses

 

     题目意思非常简单,判断所给字符串中的括号是否匹配,需要注意的问题:)(这样是不匹配的。

   

 public class Solution {
   public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        
        for(int i=0; i<s.length(); i++) {
        	if(stack.isEmpty()) {
        		stack.push(s.charAt(i));
        	} else {
        		if(isMatch(stack.peek(), s.charAt(i))) {
        			stack.pop();
        		}
        		else {
        			stack.push(s.charAt(i));
        		}
        	}
        	
        	
        }
        
        if(stack.isEmpty())
        	return true;
        else
        	return false;
		
    }
	
	public boolean isMatch(char sc, char c) {
		if(sc=='{'&&c=='}' || sc=='('&&c==')' || sc=='['&&c==']') {
			return true;
		}
		else 
			return false;
	}
}

 

posted @ 2015-04-02 20:43  Pickle  阅读(158)  评论(0编辑  收藏  举报