
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 Binary String has At Most One Segment of Ones in Python
Suppose we have a binary string s (without leading zeros), We have to check whether s contains at most one contiguous segment of ones or not.
So, if the input is like s = "11100", then the output will be True as there is one segment of ones "111".
To solve this, we will follow these steps −
count := -1
-
if size of s is same as 1, then
return True
-
for each i in s, do
-
if i is same as "1" and count > -1, then
return False
-
otherwise when i is same as "0", then
count := count + 1
-
return True
Let us see the following implementation to get better understanding −
Example
def solve(s): count = -1 if len(s)==1: return True for i in s: if i=="1" and count>-1: return False elif i=="0": count+=1 return True s = "11100" print(solve(s))
Input
11100
Output
True
Advertisements