1003. Check If Word Is Valid After Substitutions
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 int
. More formally,t
becomestleft + "abc" + tright
, wheret == tleft + tright
. Note thattleft
andtright
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'
Solutions
Solution 1: Stack
We observe the operations in the problem and find that each time a string \(\textit{"abc"}\) is inserted at any position in the string. Therefore, after each insertion operation, the length of the string increases by \(3\). If the string \(s\) is valid, its length must be a multiple of \(3\). Thus, we first check the length of the string \(s\). If it is not a multiple of \(3\), then \(s\) must be invalid, and we can directly return \(\textit{false}\).
Next, we traverse each character \(c\) in the string \(s\). We first push the character \(c\) onto the stack \(t\). If the length of the stack \(t\) is greater than or equal to \(3\), and the top three elements of the stack form the string \(\textit{"abc"}\), then we pop the top three elements from the stack. We then continue to traverse the next character in the string \(s\).
After the traversal, if the stack \(t\) is empty, it means the string \(s\) is valid, and we return \(\textit{true}\); otherwise, we return \(\textit{false}\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the string \(s\).
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|