1. 程式人生 > >[leetcode]20. Valid Parentheses

[leetcode]20. Valid Parentheses

這個題果真很easy
但是注意“【”這種這有左邊的情況

class Solution {
    public boolean isValid(String s) {
        if(s.length()==0||s==null)return true;
        
        Stack<Character> st = new Stack<Character>();
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{'){
                st.push(s.charAt(i));
               
            }
            else{
                if(!st.empty()){
                    char c=st.pop();
                    if(s.charAt(i)==')'){
                        if(c!='(')return false;
                    }
                    else if(s.charAt(i)==']'){
                        if(c!='[')return false;
                    }
                    else if(s.charAt(i)=='}'){
                        if(c!='{') return false;
                    }
                }
                else return false;
                
            }
        }
        
        if(!st.empty())return false;
        return true;
        
    }
}

論壇裡發現一個genius的程式碼。我們都看左右配對。人家直接反著push stack

public boolean isValid(String s) {
	Stack<Character> stack = new Stack<Character>();
	for (char c : s.toCharArray()) {
		if (c == '(')
			stack.push(')');
		else if (c == '{')
			stack.push('}');
		else if (c == '[')
			stack.push(']');
		else if (stack.isEmpty() || stack.pop() != c)
			return false;
	}
	return stack.isEmpty();
}