(java)leetcode-20

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.


解题思路:

这个想到了以前用栈来进行判断,就是当是左括号的时候就push,当时右括号的时候就pop,比较pop的值是不是想要的结果,如果不是就返回错误。最后检查遍历结束之后的栈是不是空栈。
网上看到了一个不错的做法,就是当遇到左括号的时候就把对应的右括号push进去,这样pop的时候直接看是不是对应的右括号就可以了。代码会简单很多。


public class Solution {
    public boolean isValid(String s) {
        Stack st = new Stack();
        for(int i = 0;i


你可能感兴趣的:(leetcode)