- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 the count of sub-strings whose characters can be rearranged to form the given word in Python
Suppose we have a string S (all letters are in lowercase), we have to find the count of all of the sub-strings of length four whose characters can be rearranged to form this word "bird".
So, if the input is like "birdb", then the output will be 2.
To solve this, we will follow these steps −
cnt := 0
for i in range 0 to size of s - 3, do
bird := an array with [0, 0, 0, 0]
for j in range i to i + 4, do
if s[j] is same as 'b', then
bird[0] := bird[0] + 1
otherwise when s[j] is same as 'i', then
bird[1] := bird[1] + 1
otherwise when s[j] is same as 'r', then
bird[2] := bird[2] + 1
otherwise when s[j] is same as 'd', then
bird[3] := bird[3] + 1
if bird is same as [1,1,1,1], then
cnt := cnt + 1
return cnt
Example
Let us see the following implementation to get better understanding −
def number_of_occurrence(s): cnt = 0 for i in range(0, len(s) - 3): bird = [0, 0, 0, 0] for j in range(i, i + 4): if s[j] == 'b': bird[0] += 1 elif s[j] == 'i': bird[1] += 1 elif s[j] == 'r': bird[2] += 1 elif s[j] == 'd': bird[3] += 1 if bird == [1,1,1,1]: cnt += 1 return cnt s = "birdb" print(number_of_occurrence(s))
Input
"birdb"
Output
2