20. Valid Parentheses

原题链接:https://leetcode.com/problems/valid-parentheses/description/
这道题目是括号匹配问题,典型的栈的应用!使用栈可以很轻松的解决之:

import java.util.Stack;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();

        System.out.println(s.isValid("()")); // true
        System.out.println(s.isValid("()[]{}")); // true
        System.out.println(s.isValid("(]")); // false
        System.out.println(s.isValid("([)]")); // false
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        char[] chars = s.toCharArray();
        int len = chars.length;
        if (len % 2 != 0) {
            return false;
        }

        for (char c : chars) {
            if (!stack.empty()) {
                char stackTopEle = stack.peek();
                switch (stackTopEle) {
                    case '(':
                        if (c == ')') {
                            stack.pop();
                            continue;
                        }
                        break;
                    case '[':
                        if (c == ']') {
                            stack.pop();
                            continue;
                        }
                        break;
                    case '{':
                        if (c == '}') {
                            stack.pop();
                            continue;
                        }
                        break;
                }
            }

            stack.push(c);
        }

        if (stack.empty()) {
            return true;
        }

        return false;
    }
}
posted @ 2018-03-10 16:24  optor  阅读(109)  评论(0编辑  收藏  举报