[LeetCode] Check If Word Is Valid After Substitutions

1003. Check If Word Is Valid After Substitutions

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isValid(string s) {
string st = "";
for(auto& ch : s) {
st.push_back(ch);
int sz = st.size();
if(sz >= 3 and st[sz-1] == 'c' and st[sz-2] == 'b' and st[sz-3] == 'a') {
st.pop_back();
st.pop_back();
st.pop_back();
}
}
return st == "";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/25/PS/LeetCode/check-if-word-is-valid-after-substitutions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.