You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
605 B

2 years ago
package class28;
public class Problem_0020_ValidParentheses {
public static boolean isValid(String s) {
if (s == null || s.length() == 0) {
return true;
}
char[] str = s.toCharArray();
int N = str.length;
char[] stack = new char[N];
int size = 0;
for (int i = 0; i < N; i++) {
char cha = str[i];
if (cha == '(' || cha == '[' || cha == '{') {
stack[size++] = cha == '(' ? ')' : (cha == '[' ? ']' : '}');
} else {
if (size == 0) {
return false;
}
char last = stack[--size];
if (cha != last) {
return false;
}
}
}
return size == 0;
}
}