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.
class Solution {
public boolean isValid(String s) {
if (s == null || s.length()==0) {
return true;
}
if (s.length() == 1) {
return false;
}
Stack<Character> stack = new Stack<>();//use stack
char[] sch = s.toCharArray();
int index = 0;
while (index < sch.length) {
if (sch[index] == '(' || sch[index] == '[' ||sch[index] == '{') {
stack.push(sch[index]);
index++;
continue;
}
if (sch[index] == ')') {
if(stack.isEmpty() || stack.pop() != '(' ) {
return false;
}
}else if (sch[index] == ']') {
if(stack.isEmpty() ||stack.pop() != '[' ) {
return false;
}
}else if (sch[index] == '}') {
if(stack.isEmpty() ||stack.pop() != '{' ) {
return false;
}
}
index++;
}
return stack.isEmpty();
}
}
class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
if (s.length() == 1) {
return false;
}
Stack<Character> stack = new Stack<>();
char[] sch = s.toCharArray();
for (char c : sch) {
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();
}
}