Post

Valid Parentheses

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

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
class Solution {
    public boolean isValid(String s) {
        if (s.length() < 2) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char curr = s.charAt(i);
            // if current character matach left parenthese
            if (curr == '(' || curr == '[' || curr == '{') {
                stack.push(curr);
                continue;
            } 
            // if current character matach right parenthese, else return false
            if (!stack.isEmpty()) {
                if (curr == ')' && stack.peek() == '(') {
                    stack.pop();
                } else if (curr == ']' && stack.peek() == '[') {
                    stack.pop();
                } else if (curr == '}' && stack.peek() == '{') {
                    stack.pop();
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }

        return stack.isEmpty();
    }
}

Complexity

  • Time = O(n)
  • Space = O(n)
This post is licensed under CC BY 4.0 by the author.