
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
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
- if flag is True, then
- otherwise,
- index := index + 1
- if string[index] is same as c, then
- return True
Let us see the following implementation to get better understanding −
Example
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
Advertisements