Title description
Given a string containing only the characters'(',')','{','}','[' and']', determine whether the given string is a legal bracket sequence. The
brackets must be correct The order is closed, "()" and "()[]{}" are both legal bracket sequences, but "(]" and "([)]" are illegal.
Example 1
enter
"["
return value
false
Example 2
enter
"[]"
return value
true
Code implementation :
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return bool布尔型
*/
public boolean isValid (String s) {
char[] arr = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (char a : arr) {
if (a == '(' || a == '{' || a == '[') {
stack.push(a);
} else {
if (stack.empty()) {
return false;
}
if ((stack.peek() == '(' && a == ')') ||
(stack.peek() == '{' && a == '}') ||
(stack.peek() == '[' && a == ']')) {
stack.pop();
}
}
}
if (stack.empty()) {
return true;
} else {
return false;
}
}
}