Skip to content

1003. Check If Word Is Valid After Substitutions

Difficulty Topics

Description

Given a string s, determine if it is valid.

A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:

  • Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty.

Return true if s is a valid string, otherwise, return false.

 

Example 1:

Input: s = "aabcbc"
Output: true
Explanation:
"" -> "abc" -> "aabcbc"
Thus, "aabcbc" is valid.

Example 2:

Input: s = "abcabcababcc"
Output: true
Explanation:
"" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
Thus, "abcabcababcc" is valid.

Example 3:

Input: s = "abccba"
Output: false
Explanation: It is impossible to get "abccba" using the operation.

 

Constraints:

  • 1 <= s.length <= 2 * 104
  • s consists of letters 'a', 'b', and 'c'

Solution

check-if-word-is-valid-after-substitutions.py
class Solution:
    def isValid(self, s: str) -> bool:
        s = list(s)

        while len(s) > 0:
            count = 0
            stack = []

            for x in s:
                if x == "a":
                    count = 1
                elif x == "b" and count == 1:
                    count = 2
                elif x == "c" and count == 2:
                    count = 3
                else:
                    count = 0

                stack.append(x)

                if count == 3:
                    for _ in range(3):
                        stack.pop()
                    count = 0

            if len(s) == len(stack): return False
            s = stack


        return len(s) == 0