20. Valid Parentheses

来源:互联网 发布:用友软件凭证打印 编辑:程序博客网 时间:2024/06/06 00:11

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.

import java.util.Stack;public class Solution {    public boolean isValid(String s) {        Stack<Character> stack = new Stack<Character>();        //使用foreach循环        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();    }}
原创粉丝点击