Skip to content
LC-1003 Medium LeetCode

1003. Check If Word Is Valid After Substitutions

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 60% Topics: String, Stack
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(n)

class Solution(object):
    def isValid(self, S):
        """
        :type S: str
        :rtype: bool
        """
        stack = []
        for i in S:
            if i == 'c':
                if stack[-2:] == ['a', 'b']:
                    stack.pop()
                    stack.pop()
                else:
                    return False
            else:
                stack.append(i)
        return not stack

Solution from kamyu104/LeetCode-Solutions · MIT

Similar questions