[leetcode]Valid Parentheses

题目描述如下:

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.

easy题,使用一个栈,然后逐个字符进行判断即可。代码如下:

public class Solution {
    public boolean isValid(String s) {
               Stack<Character> stack = new Stack<>();
        if(s.length() == 0) return true;
        boolean flag = true;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            switch (ch){
                case ')':
                    if(stack.isEmpty() || stack.peek() != '('){
                        stack.push(ch);
                        flag = false;
                    }
                    else
                        stack.pop();
                    break;
                case '}':
                    if(stack.isEmpty() || stack.peek() != '{'){
                        stack.push(ch);
                        flag = false;
                    }
                    else
                        stack.pop();
                    break;
                case ']':
                    if(stack.isEmpty() || stack.peek() != '['){
                        stack.push(ch);
                        flag = false;
                    }
                    else
                        stack.pop();
                    break;
                default:
                    stack.push(ch);
                    break;
            }
            if(!flag) break;
        }
        return stack.isEmpty();
    }
}

题目链接:https://leetcode.com/problems/valid-parentheses/

你可能感兴趣的:(LeetCode)