# 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 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'

## 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$.

• class Solution {
public boolean isValid(String s) {
if (s.length() % 3 > 0) {
return false;
}
StringBuilder t = new StringBuilder();
for (char c : s.toCharArray()) {
t.append(c);
if (t.length() >= 3 && "abc".equals(t.substring(t.length() - 3))) {
t.delete(t.length() - 3, t.length());
}
}
return t.isEmpty();
}
}

• class Solution {
public:
bool isValid(string s) {
if (s.size() % 3) {
return false;
}
string t;
for (char c : s) {
t.push_back(c);
if (t.size() >= 3 && t.substr(t.size() - 3, 3) == "abc") {
t.erase(t.end() - 3, t.end());
}
}
return t.empty();
}
};

• 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 t


• func isValid(s string) bool {
if len(s)%3 > 0 {
return false
}
t := []byte{}
for i := range s {
t = append(t, s[i])
if len(t) >= 3 && string(t[len(t)-3:]) == "abc" {
t = t[:len(t)-3]
}
}
return len(t) == 0
}

• function isValid(s: string): boolean {
if (s.length % 3 !== 0) {
return false;
}
const t: string[] = [];
for (const c of s) {
t.push(c);
if (t.slice(-3).join('') === 'abc') {
t.splice(-3);
}
}
return t.length === 0;
}