给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需要满足:
左括号必须用相同类型的右括号闭合。例如:"[]","()","{}"
左括号必须以正确的顺序闭合。例如:"[()]"
每个右括号都有一个对应的相同类型的左括号。例如:"[()]{}"
- package learnProject.csdn;
-
- /**
- *
- * @author Roc-xb
- *
- */
- public class ValidParentheses {
-
- public static boolean isValid(String s) {
- if (s == null || s.length() == 0)
- return false;
- char[] stack = new char[s.length()];
- int head = 0;
- for (char c : s.toCharArray()) {
- switch (c) {
- case '{':
- case '[':
- case '(':
- stack[head++] = c;
- break;
- case '}':
- if (head == 0 || stack[--head] != '{') {
- return false;
- }
- break;
- case ')':
- if (head =