#20 Valid Parentheses

来源:互联网 发布:windows 桌面路径 编辑:程序博客网 时间:2024/06/07 18:34

题目:

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.

题解:

考察栈的基本使用,简单的入栈和出栈即可解决。刚看到了一种好玩的for循环格式,这里用一下。

public class Solution {    public boolean isValid(String s) {        Stack<Character> stackS = new Stack<Character>();        char[] arr = s.toCharArray();        for (char c : arr) {            if(stackS.isEmpty()){                stackS.push(c);                continue;            }            Character temp = stackS.pop();                        // 配对时c不入栈            if (temp == '[' && c == ']') {            } <span style="white-space:pre"></span>    else if (temp == '(' && c == ')') {<span style="white-space:pre"></span>    }<span style="white-space:pre"></span>    else if (temp == '{' && c == '}') {<span style="white-space:pre"></span>    }<span style="white-space:pre"></span>    <span style="white-space:pre"></span>    <span style="white-space:pre"></span>    // 不配对时c入<span style="white-space:pre"></span>    else {<span style="white-space:pre"></span>        stackS.push(temp);<span style="white-space:pre"></span>        stackS.push(c);<span style="white-space:pre"></span>    }        }        return stackS.isEmpty();    }}


0 0