Check If Word Is Valid After Substitutions — LeetCode 1003 Python Solution
- Problem
- #1003
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- s = "aabcbc"
- Output
- true
- Explanation
- "" -> "abc" -> "aabcbc"
Python solution
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 3:
return False
t = []
for c in s:
t.append(c)
if ''.join(t[-3:]) == 'abc':
t[-3:] = []
return not tComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1003. Check If Word Is Valid After Substitutions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1003. Check If Word Is Valid After Substitutions?
- LeetCode 1003. Check If Word Is Valid After Substitutions is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1003. Check If Word Is Valid After Substitutions?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1003. Check If Word Is Valid After Substitutions?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1003. Check If Word Is Valid After Substitutions cover?
- LeetCode 1003. Check If Word Is Valid After Substitutions is tagged Stack and String on LeetCode.