
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Distinct Substrings in a Given String in Python
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
- for each has_let in visited[ind-1], do
- 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
Advertisements