20. 有效的括號

Approach1:
The basic idea is to push the right parentheses ‘)’, ‘]’, or ‘}’ into the stack each time when we encounter left ones. And if a right bracket appears in the string, we need check if the stack is empty and also whether the top element is the same with that right bracket. If not, the string is not a valid one. At last, we also need check if the stack is empty.

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



 public boolean isValid(String s) {
        if(s == null || s.length() %2 != 0)
            return false;
        Stack<Character> stack = new Stack<>();

        for(char c:s.toCharArray()){
            if(c == '(' ||c == '{' || c == '['){
                stack.push(c);
            }
            else{
                if(stack.empty()) return false;
                if(c == ')' && stack.pop()!= '(') return false;
                if(c == ']' && stack.pop()!= '[') return false;
                if(c == '}' && stack.pop()!= '{') return false;
            }
        }
        return stack.empty();
    }




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章