DEV Community

hwangs12
hwangs12

Posted on

c++ - valid parenthesis

Still not fully understood but here's the solution

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, char> bracketHash;

        bracketHash['{'] = '}';
        bracketHash['['] = ']';
        bracketHash['('] = ')';

        stack<char> st;

        char last;

        int checkVal;

        if (s.length() == 0)
        {
            return true;
        }

        if (s[0] == '}' || s[0] == ']' || s[0] == ')')
        {
            return false;
        }

        for (int i = 0; i < s.size(); ++i)    
        {
            if (s[i] == '{' || s[i] == '(' || s[i] == '[')
            {
                st.push(s[i]);
            }

            else
            {

                if (st.empty())
                {
                    return false;
                }
                else if (s[i] != bracketHash[st.top()])
                {
                    return false;
                }
                st.pop();
            }
        }


        return st.empty();
    }
};
Enter fullscreen mode Exit fullscreen mode

You might wonder why I post then. I know I solved this in Python. Just adopted the same logic. Still long way to go to think like a computer. I need time to understand. I mean I understand all the methods and why it works but did not run loop myself to simulate long bracket in my head.

Top comments (0)