Leetcode 20 Solution

This article provides solution to leetcode question 20 (valid-parentheses)

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

Thinking Process

This is a very classic question. Use stack to check the validness of parenthesis.

Time & Space Complexity

Assuming N is the length of the string

  • Time complexity: O(N)
  • Space complexity: O(1)

Solution

class Solution {
public:
    bool isValid(string s) {
        stack<char> a;

        for (int i = 0; i < s.length(); i++)
        {
            char ch = s[i];
            if (ch == '(' || ch == '[' || ch == '{')
                a.push(ch);
            else if (ch == ')' || ch == ']' || ch == '}')
            {
                if (a.empty())
                    return false;

                char ch2 = a.top();
                a.pop();

                if (ch == ')' && ch2 != '(')
                    return false;
                else if (ch == ']' && ch2 != '[')
                    return false;
                else if (ch == '}' && ch2 != '{')
                    return false;
            }
        }

        return a.empty();
    }
};