Leetcode 1003: Check If Word Is Valid After Substitutions

grid47
grid47
Exploring patterns and algorithms
Jul 29, 2024 5 min read

You are given a string s consisting of only the characters ‘a’, ‘b’, and ‘c’. A string is considered valid if it can be formed by repeatedly inserting the substring ‘abc’ into any position of an empty string. Your task is to determine if s can be a valid string after performing this operation any number of times.
Problem
Approach
Steps
Complexity
Input: The input is a string s of length n (1 <= n <= 2 * 10^4), consisting of only the characters 'a', 'b', and 'c'.
Example: s = 'abccba'
Constraints:
• 1 <= s.length <= 2 * 10^4
• s consists of only the characters 'a', 'b', and 'c'.
Output: Return true if the string s is valid, otherwise return false.
Example: Output: true
Constraints:
• The output will be a boolean value.
Goal: To determine if a string can be formed by inserting 'abc' into an empty string any number of times.
Steps:
• Use a stack to track the characters 'a', 'b', and 'c'.
• Iterate through the string. If a 'c' is encountered, check if the last two characters in the stack are 'b' and 'a', respectively.
• If the stack is valid after processing all characters in s, return true. Otherwise, return false.
Goal: Ensure the solution works efficiently within the given constraints.
Steps:
• The solution must handle strings of length up to 20,000.
Assumptions:
• The input string only contains 'a', 'b', and 'c'.
Input: Input: s = 'abcabc'
Explanation: The string 'abcabc' is valid because it can be formed by repeatedly inserting 'abc' into an empty string: '' -> 'abc' -> 'abcabc'.

Input: Input: s = 'aabcbc'
Explanation: The string 'aabcbc' is valid because it can be formed by inserting 'abc' into the string: '' -> 'abc' -> 'aabcbc'.

Input: Input: s = 'abccba'
Explanation: The string 'abccba' is invalid because it is impossible to form it by inserting 'abc' into an empty string.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus