20. Valid Parentheses

判断括号顺序是否正确,用栈

  1. 考虑空输入、可能含有空格、超长输入
  2. 先获取字符串长度,并依此建立数组(栈)
  3. 若为左括号,入栈;
  4. 若为右括号,对比是否与栈顶元素相同,若是,则栈顶出栈,继续进行直到末尾;若不同,则直接返回false

直接求解
结果:AC

这是排名第一的答案,真的好简洁,我写的和他的一比较简直一坨**

public boolean isValid(String s) {
    Stack stack = new Stack();
    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();
}

你可能感兴趣的:(20. Valid Parentheses)