Check if all occurrences of a character appear together in Python


Suppose we have a string s and another character c, we have to check whether all occurrences of c appear together in s or not. If the character c is not present in s then also return true.

So, if the input is like s = "bbbbaaaaaaaccddd", c = 'a', then the output will be True.

To solve this, we will follow these steps −

  • flag := False
  • index := 0
  • n := size of string
  • while index < n, do
    • if string[index] is same as c, then
      • if flag is True, then
        • return False
      • while index < n and string[index] is same as c, do
        • index := index + 1
      • flag := True
    • otherwise,
      • index := index + 1
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(string, c) :
   flag = False
   index = 0
   n = len(string)
   while index < n:
      if string[index] == c:
         if (flag == True) :
            return False
         while index < n and string[index] == c:
            index += 1
         flag = True
      else :
         index += 1
   return True
s = "bbbbaaaaaaaccddd"
c = 'a'
print(solve(s, c))

Input

"bbbbaaaaaaaccddd", "a"

Output

True

Updated on: 29-Dec-2020

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements