Lc20-Valid Parentheses

import java.util.Stack;

/*
 * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true
Example 2:

Input: "()[]{}"
Output: true
Example 3:

Input: "(]"
Output: false
Example 4:

Input: "([)]"
Output: false
Example 5:

Input: "{[]}"
Output: true

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 */
public class Lc20 {
    public static boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        boolean isValid = false;

        char[] ch = s.toCharArray();
        for (char c : ch) {
            if ('(' == c) {
                stack.push(c);
            } else if ('[' == c) {
                stack.push(c);
            } else if ('{' == c) {
                stack.push(c);
            } else if (!stack.isEmpty()) {
                if (')' == c) {
                    Character temp = stack.pop();
                    if ('(' != temp) {
                        return false;
                    }
                } else if (']' == c) {
                    Character temp = stack.pop();
                    if ('[' != temp) {
                        return false;
                    }
                } else if ('}' == c) {
                    Character temp = stack.pop();
                    if ('{' != temp) {
                        return false;
                    }
                }
            } else {
                return false;
            }

        }
        if (stack.isEmpty()) {
            isValid = true;
        }
        return isValid;
    }

    public static void main(String[] args) {
        String s = "{";
        System.out.println(isValid(s));
    }

}
posted @ 2020-01-14 11:22  小傻孩丶儿  阅读(104)  评论(0编辑  收藏  举报