[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();
}

猜你喜欢

转载自blog.csdn.net/weixin_36869329/article/details/84394485