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 −

Example

 Live Demo

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

Input

“abcabcababcc”

Output

1

Updated on: 02-May-2020

218 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements