Count Substrings That Can Form 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 −

 Live Demo

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
Updated on: 2020-08-19T11:41:47+05:30

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements