Program to find out number of distinct substrings in a given string in python

PythonServer Side ProgrammingProgramming

Suppose, we are given a substring denoted by 's'. We have to find out the unique substrings and return the number of these substrings as output.

So, if the input is like s = 'prrstvt', then the output will be 26.

The distinct substrings will be −

'pr', 'rrs', 'st', 'rr', 'tv', 'rstv', 'stvt', 'prrstv', 'prrstvt', 'rrstvt', 's', 'prrst', 'stv', 'rrstv', 'rst', 'v', 'tvt', 'rstvt', 'r', 'rs', 'vt', 't', 'prr', 'p', 'rrst', and 'prrs'.

To solve this, we will follow these steps −

  • visited := a new map
  • for each index ind, and value let in s, do
    • temp := a new set
    • if ind-1 is present in visited, then
      • for each has_let in visited[ind-1], do
        • add(has_let + let) to list temp
    • add(let) to list temp
    • visited[ind] := temp
  • res := a new set
  • for each sets in visited, do
    • add(visited[sets]) to res
  • return size of res

Example

Let us see the following implementation to get better understanding −

def solve(s):
   visited = dict()
   for ind, let in enumerate(s):
      temp = set()
      if ind-1 in visited:
         for has_let in visited[ind-1]:
            temp.add(has_let+let)
      temp.add(let)
      visited[ind] = temp
   res = set()
   for sets in visited:
      res.update(visited[sets])
   return len(res)

print(solve('prrstvt'))

Input

'prrstvt'

Output

26
raja
Updated on 06-Oct-2021 11:28:03

Advertisements