Unique Substrings in Wraparound String in C++

C++Server Side ProgrammingProgramming

Suppose we have the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so the value s will look like this − "...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".

Now we have another string p. Our job is to find out how many unique non-empty substrings of p are present in s. In particular, our input is the string p and we need to output the number of different non-empty substrings of p in the string s.

So if the input is like “zab” the output will be 6. There are 6 substrings “z”, “a”, “b”, “za”, “ab”, “zab” of the string “zab” in the string s

To solve this, we will follow these steps −

  • Create an array dp of size 26, set x := 0

  • for I in range 0 to the size of p

    • if i > 0 and (p[i] – p[i – 1] is 1 or p[i – 1] – p[i] is 25), then increase x by 1, otherwise set x := 1

    • dp[p[i] – ASCII of ‘a’] := maximum of (x, dp[p[i] – ASCII of ‘a’])

  • ret := 0

  • for I in range 0 to 25

    • ret := ret + dp[i]

  • return ret

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findSubstringInWraproundString(string p) {
      vector <int> dp(26);
      int x = 0;
      for(int i = 0; i < p.size(); i++){
         if(i > 0 && (p[i] - p[i - 1] == 1 || p[i - 1] - p[i] == 25)){
            x++;
         }
         else x = 1;
            dp[p[i] - 'a'] = max(x, dp[p[i] - 'a']);
      }
      int ret = 0;
      for(int i = 0; i < 26; i++){
         ret += dp[i];
      }
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.findSubstringInWraproundString("zab"));
}

Input

"zab"

Output

6
raja
Published on 31-Mar-2020 08:55:28
Advertisements