본문 바로가기

C

c++ leetcode 1249 Minimum Remove to make valid parenthesis 문제풀이

코드 >>

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Solution {
public:
    bool isPushAble(char c)
    {
        if ((c == '{'|| (c == '('|| (c == '['))
        {
            return true;
        }
        else
            return false;
    }
 
    set<int> getToBeDeletedIndex(string s) 
    {
        int sSize = (int)s.size();
            
        unordered_map<charchar> hash;
        hash['}'= '{';
        hash[')'= '(';
        hash[']'= '[';
        stack<pair<charint>> charStack;
        set<int> closeIndex;
        for (int i = 0; i < sSize; i++)
        {
            if (isalpha(s[i]))
                continue;
            else
            {
                if (this->isPushAble(s[i]))
                {
                    charStack.push({ s[i], i });
                    //cout << "stack pushed : " << s[i] << endl;
                }
                    
                else
                {
                    if (!charStack.empty()) {
                        if (charStack.top().first == hash[s[i]])
                            charStack.pop();
                        else
                            closeIndex.insert(i);
                    }
                    else
                        closeIndex.insert(i);
                }                
            }            
        }
 
        if (!charStack.empty())
        {
            size_t stackSize = charStack.size();
                
            for (size_t i = 0; i < stackSize; i++)
            {
                closeIndex.insert(charStack.top().second);
                charStack.pop();
            }
            return closeIndex;
        }
        else
        {
            return closeIndex;
        }
    }
    string minRemoveToMakeValid(string s) {
        set<int> tobeDeletedSet = this->getToBeDeletedIndex(s);
        string temp;
        for (int i=0; i<s.size(); i++)
        {
            if (tobeDeletedSet.find(i) == tobeDeletedSet.end())
                temp.push_back(s[i]);
        }
        return temp;
    }
};