20. Valid Parentheses

 

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


Algorithm

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
42
43
44
45
46
47
48
49
50
51
52
53
54
> FUNCTION main(): O(n), n = length of input string
- DO      Read user input and return problem output
- INPUT   s (input string): string
- OUTPUT  validness of INPUT: bool

GLOBAL st ← empty stack
FOR each character c, index i in s
    CALL validness ← check(c, i)
    IF validness is False THEN
        return False
IF st is not empty THEN
    return False
return True

---

> FUNCTION check(): O(1)
- DO      Read a character and return if it's valid under some conditions
- INPUT   c (checked character): character, i (index of character): integer
- OUTPUT  validness of INPUT: bool

CALL c ← convert(c)
IF st is empty THEN
    IF c % 2 = 0 THEN
        return False
    ELSE
        push c to st
        return True
top ← top element of st
IF c - top != 1 THEN
    IF c % 2 = 0 THEN
        return False
    ELSE
        push c to st
        return True
ELSE
    pop st
    return True

---

> FUNCTION convert(): O(1)
- DO      Read a character and return a converted integer
- INPUT   c: character
- OUTPUT  converted integer: integer

CASE c OF
    ( : return 1
    ) : return 2
    { : return 3
    } : return 4
    [ : return 5
    ] : return 6
exit with error code -1 (Input string includes unexpected character)


Code

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
42
43
44
45
46
class Solution:
    def __init__(self):
        self.st = []

    def isValid(self, s: str) -> bool:
        for i, c in enumerate(s):
            if not self.check(c, i):
                return False
        if len(self.st) != 0:
            return False
        return True

    def check(self, c, i):
        c = self.convert(c)
        if len(self.st) == 0:
            if c % 2 == 0:  # )
                return False
            else:  # (
                self.st.append(c)
                return True

        top = self.st[-1]  # 1
        if c - top != 1:
            if c % 2 == 0:  # ()
                return False
            else:  # ()
                self.st.append(c)  # 1
                return True
        else:
            self.st.pop()
            return True

    def convert(self, c):
        if c == '(':
            return 1
        elif c == ')':
            return 2
        elif c == '{':
            return 3
        elif c == '}':
            return 4
        elif c == '[':
            return 5
        elif c == ']':
            return 6
        exit(-1)
Runtime: 24 ms, faster than 89.69% of Python3 online submissions for Valid Parentheses.
Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Valid Parentheses.

55분 소요