来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses/

描述

给定一个只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:
输入: “()”
输出: true

示例 2:
输入: “()[]{}”
输出: true

示例 3:
输入: “(]”
输出: false

示例 4:
输入: “([)]”
输出: false

题解

  1. class Solution {
  2. Map<Character, Character> mappings = new HashMap<Character, Character>() {{
  3. put(')', '(');
  4. put('}', '{');
  5. put(']', '[');
  6. }};
  7. public boolean isValid(String s) {
  8. Stack<Character> stack = new Stack<Character>();
  9. for (int i = 0; i < s.length(); i++) {
  10. char c = s.charAt(i);
  11. if (mappings.containsKey(c)) {
  12. char topElement = stack.empty() ? '#' : stack.pop();
  13. if (topElement != mappings.get(c)) {
  14. return false;
  15. }
  16. } else {
  17. stack.add(c);
  18. }
  19. }
  20. return stack.isEmpty();
  21. }
  22. }

复杂度分析

  • 时间复杂度:20. 有效的括号(Valid Parentheses) - 图1
  • 空间复杂度:20. 有效的括号(Valid Parentheses) - 图2