2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_20.java 1.22 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2020-08-09 20:39 . optimize solutions
package com.hit.basmath.learn.queue_stack;
import java.util.Stack;
/**
* 20. Valid Parentheses
* <p>
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
* <p>
* An input string is valid if:
* <p>
* Open brackets must be closed by the same type of brackets.
* Open brackets must be closed in the correct order.
* Note that an empty string is also considered valid.
* <p>
* Example 1:
* <p>
* Input: "()"
* Output: true
* <p>
* Example 2:
* <p>
* Input: "()[]{}"
* Output: true
* <p>
* Example 3:
* <p>
* Input: "(]"
* Output: false
* <p>
* Example 4:
* <p>
* Input: "([)]"
* Output: false
* <p>
* Example 5:
* <p>
* Input: "{[]}"
* Output: true
*/
public class _20 {
public boolean isValid(String s) {
Stack<Character> 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();
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助