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.

解题思路:使用一个栈临时存储,这样就可以比较相邻的元素。

package stringTest;

import java.util.Stack;

public class isValiad {

    public static boolean isValid(String s) {
        if (s.length() == 0 || s.equals(""))
            return false;
        char[] c = s.toCharArray();
        if (c.length == 1)
            return false;
        int n = s.length();
        Stack<Character> sta = new Stack<Character>();

        for (int i = 0; i < n; i++) {
            if (sta.isEmpty()) {
                sta.push(c[i]);
            } else {
                if ((c[i] == ')' && sta.peek() == '(')
                        || (c[i] == '}' && sta.peek() == '{')
                        || (c[i] == ']' && sta.peek() == '[')) {
                    sta.pop();
                    continue;
                } else {
                    sta.push(c[i]);
                }
            }
        }
        return sta.isEmpty();
    }

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

}

你可能感兴趣的:(String,stack)