20. Valid Parentheses

20. Valid Parentheses

Description

Difficulty: Easy

Related Topics: String, Stack

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

1
2
Input: s = "()"
Output: true

Example 2:

1
2
Input: s = "()[]{}"
Output: true

Example 3:

1
2
Input: s = "(]"
Output: false

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

Hints/Notes

Solution

Language: C++

Cleaner solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> m = {
{')', '('},
{']', '['},
{'}', '{'},
};
stack<char> stk;
for (char c : s) {
if (!m.contains(c)) {
stk.push(c);
} else {
if (stk.empty() || stk.top() != m[c]) {
return false;
} else {
stk.pop();
}
}
}
return stk.empty();
}
};
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 {
public:
    bool isValid(string s) {
        stack<char> stk;
        for (char c : s) {
            switch(c) {
                case '(':
                    stk.push(c);
                    break;
                case ')':
                    if (stk.empty() || stk.top() != '(') {
                        return false;
                    } else {
                        stk.pop();
                    }
                    break;
                case '[':
                    stk.push(c);
                    break;
                case ']':
                    if (stk.empty() || stk.top() != '[') {
                        return false;
                    } else {
                        stk.pop();
                    }
                    break;
                case '{':
                    stk.push(c);
                    break;
                case '}':
                    if (stk.empty() || stk.top() != '{') {
                        return false;
                    } else {
                        stk.pop();
                    }
                    break;
            }
        }
        return stk.empty();
    }
};