Given a string s that only includes '(', ')', '{', '}', '[', ']', determine whether the string is valid.
To be a valid string,
the opening bracket must be closed by a closing bracket of the same type. For example: "[]", "()", "{}"
The left brackets must be closed in the correct order. For example: "[()]"
Each right bracket has a corresponding left bracket of the same type. For example:"[()]{}"
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 == 0 || stack[--head] != '(') {
return false;
}
break;
case ']':
if (head == 0 || stack[--head] != '[') {
return false;
}
break;
}
}
return head == 0;
}
public static void main(String[] args) {
System.out.println(isValid(null));
}
}