1 题目

有效的括号

2 解

2.1 我的解

  • 时间复杂度 O(n)
  • 空间复杂度 O(n)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
    public boolean isValid(String s) {
        Stack stack = new Stack();
        char[] arr = s.toCharArray();
        for (char c : arr) {
            switch (c) {
                case '(': stack.push(c); break;
                case '{': stack.push(c); break;
                case '[': stack.push(c); break;
                case ')': {
                    if (stack.empty() || !('(' == (char) stack.pop())) {
                        return false;
                    }
                    break;
                }
                case '}': {
                    if (stack.empty() || !('{' == (char) stack.pop())) {
                        return false;
                    }
                    break;  
                }
                case ']': {
                    if (stack.empty() || !('[' == (char) stack.pop())) {
                        return false;
                    }
                    break;  
                }
            }
        }
        if (!stack.empty()) {
            return false;
        }
        return true;
    }
}

2.2 官方的解

官方的解真是牛逼,同样是用栈,人家写出来的代码扩展性如此好,那么优雅,我这个解耦合度高的都看不下去了。

  • 时间复杂度 O(n)
  • 空间复杂度 O(n)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {

  // Hash table that takes care of the mappings.
  private HashMap<Character, Character> mappings;

  // Initialize hash map with mappings. This simply makes the code easier to read.
  public Solution() {
    this.mappings = new HashMap<Character, Character>();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }

  public boolean isValid(String s) {

    // Initialize a stack to be used in the algorithm.
    Stack<Character> stack = new Stack<Character>();

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      // If the current character is a closing bracket.
      if (this.mappings.containsKey(c)) {

        // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
        char topElement = stack.empty() ? '#' : stack.pop();

        // If the mapping for this bracket doesn't match the stack's top element, return false.
        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } else {
        // If it was an opening bracket, push to the stack.
        stack.push(c);
      }
    }

    // If the stack still contains elements, then it is an invalid expression.
    return stack.isEmpty();
  }
}