본문 바로가기

C

c++ leet code 20. Valid Parentheses stack solution

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 {
public:
    bool isPushAble(char c)
    {
        if ((c == '{'|| (c == '('|| (c == '['))
        {
            return true;
        }
        else
            return false;
    }
 
    bool isValid(string s) {
        int sSize = (int)s.size();
        if (sSize == 0 || sSize == 1)
            return false;
        
        unordered_map<charchar> hash;
        hash['}'= '{';
        hash[')'= '(';
        hash[']'= '[';
        stack<char> charStack;
        for (int i = 0; i < sSize; i++)
        {
            if (isPushAble(s[i]))
                charStack.push(s[i]);
            else
                
            {
                if (!charStack.empty()) {
                    if (charStack.top() == hash[s[i]])
                        charStack.pop();
                    else
                        return false;
                }
                else
                    return false;
            }
        }
 
        if (charStack.empty())
            return true;
        else
            return false;
    }
};