Check If Word Is Valid After Substitutions in C++

Suppose we are given that the string "abc" is valid. So from any valid string V, we can divide V into two pieces X and Y such that X + Y is same as V. (X or Y may be empty.). Then, X + "abc" + Y is also valid. So for example S = "abc", then examples of valid strings are: "abc", "aabcbc", "abcabc", "abcabcababcc". And some examples of invalid strings are: "abccba", "ab", "cababc", "bac". We have to check true if and only if the given string S is valid.

So if the input is like “abcabcababcc”, then that is valid, so output will be true.

To solve this, we will follow these steps −

  • define a stack st

  • for i in range 0 to size of S

    • if st is empty or S[i] is not same as ‘c’, then push S[i] into stack

    • otherwise

      • insert c into the st

      • while size of st >= 3

        • c := top of st and pop the top element from st

        • b := top of st and pop the top element from st

        • a := top of st and pop the top element from st

        • temp := temp concatenate with a

        • temp := temp concatenate with b

        • temp := temp concatenate with c

        • if temp is “abc”, then go for next iteration

        • otherwise

          • push a, then b, then c into st, and break the loop

    • return true, when the st is empty, otherwise return false

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   bool isValid(string S) {
      stack <char> st;
      for(int i = 0; i < S.size(); i++){
         if(st.empty() || S[i] != 'c'){
            while(st.size() >= 3){
               char c =;
               char b =;
               char a =;
               string temp = "";
               temp += a;
               temp += b;
               temp += c;
               if(temp == "abc"){
      return st.empty();
   Solution ob;
   cout << (ob.isValid("abcabcababcc"));