https://leetcode-cn.com/problems/valid-parentheses/

  1. public boolean isValid(String s) {
  2. Stack<Character> stack = new Stack<>();
  3. char[] str = s.toCharArray();
  4. for (char c : str) {
  5. if (c == '(' || c == '{' || c == '[') {
  6. stack.push(c == '(' ? ')' : (c == '{' ? '}' : ']'));
  7. } else {
  8. if (stack.isEmpty()) {
  9. return false;
  10. }
  11. if (c != stack.pop()) {
  12. return false;
  13. }
  14. }
  15. }
  16. return stack.isEmpty();
  17. }