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,tbecomestleft + "abc" + tright, wheret == tleft + tright. Note thattleftandtrightmay 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 * 104sconsists of letters'a','b', and'c'
Solutions
Solution 1: Stack
If the string is valid, it’s length must be the multiple of $3$.
We traverse the string and push every character into the stack $t$. If the size of stack $t$ is greater than or equal to $3$ and the top three elements of stack $t$ constitute the string "abc", we pop the top three elements. Then we continue to traverse the next character of the string $s$.
When the traversal is over, if the stack $t$ is empty, the string $s$ is valid, return true, otherwise return false.
The time complexity is $O(n)$ and the space complexity is $O(n)$. Where $n$ is the length of the string $s$.
| |
| |
| |
| |
| |
