
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count number of distinct substrings in s in Python
Suppose we have a string s, we have to find the number of distinct non-empty substrings of s.
So, if the input is like s = "abaa", then the output will be 8 because, the substrings are ["a", "b", "ab", "ba", "aa", "aba", "baa", "abaa"].
To solve this, we will follow these steps −
- trie := a new map
- n := size of s
- for i in range 0 to n - 1, do
- curr := trie
- for j in range i to n - 1, do
- c := s[j]
- if c not in curr, then
- curr[c] := a new map
- curr := curr[c]
- curr["*"] := True
- q := make a queue, and insert trie
- ans := 0
- while q is non-empty, do
- ans := ans + 1
- t := left item of q, and delete this item from q
- for each c in t, do
- if c is not same as "*", then
- insert t[c] at the end of q
- if c is not same as "*", then
- return ans - 1
Example
Let us see the following implementation to get better understanding −
from collections import deque def solve(s): trie = {} n = len(s) for i in range(n): curr = trie for j in range(i, n): c = s[j] if c not in curr: curr[c] = {} curr = curr[c] curr["*"] = True q = deque([trie]) ans = 0 while q: ans += 1 t = q.popleft() for c in t: if c != "*": q.append(t[c]) return ans - 1 s = "abaa" print(solve(s))
Input
"abaa"
Output
8
- Related Articles
- Program to count number of palindromic substrings in Python
- Program to count number of homogenous substrings in Python
- Program to find out number of distinct substrings in a given string in python
- Count number of substrings with exactly k distinct characters in C++
- Program to count number of similar substrings for each query in Python
- Program to count number of distinct characters of every substring of a string in Python
- Program to count maximum score from removing substrings in Python
- Count substrings made up of a single distinct character
- Program to count substrings that differ by one character in Python
- Program to find number of distinct subsequences in Python
- Program to count substrings with all 1s in binary string in Python
- Python program to count distinct words and count frequency of them
- Program to count maximum number of distinct pairs whose differences are larger than target in Python
- Python program to find N-sized substrings with K distinct characters
- Program to find maximum number of non-overlapping substrings in Python

Advertisements