1. 程式人生 > >20. Valid Parentheses leetcode java

20. Valid Parentheses leetcode java

1.題目

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.

給定一個包含(){}[]的字串,判斷它是否是有效括號。

2.思路

用棧解決這個問題,用兩個棧,s1和s2,s1裡按序push進字串s

①如果s2不為空,取s1和s2棧頂字元進行比較,如果滿足isequal那麼s2的棧頂pop掉

②如果s2為空,那麼將s1棧頂push進s2

迴圈結束如果s2為空,那麼這個字元有效,否則無效。

isequal函式的功能在於看傳到這個函式的兩個字元是否能配成一對,而且是有序的一對,比如“()“是一對,但是“)(”不是。

注意字串相等不能用==,而是要用equals()函式。

3.程式

class Solution {
    public boolean isValid(String s) {
        Stack<String> s1=new Stack<String>();
        Stack<String> s2=new Stack<String>();
        String temp;
        for(int i=0;i<s.length();i++){
            s1.push(s.substring(i,i+1));
        }
        while(!s1.isEmpty()){
            temp=s1.pop();
            if(!s2.isEmpty()){
                if(isequal(temp,s2.peek())) {
                	s2.pop();
                }
                else {
                	s2.push(temp);
                }
            }
            else
            	s2.push(temp);
        }
        if(s2.isEmpty())
        	return true;
        return false;
    }	
    public boolean isequal(String a,String b) {
    	if((a.equals("{")&&b.equals("}"))||(a.equals("[")&&b.equals("]"))||(a.equals("(")&&b.equals(")")))
    		return true;
    	return false;
    }
}