[LeetCode] Check if Binary String Has at Most One Segment of Ones

1784. Check if Binary String Has at Most One Segment of Ones

Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
bool checkOnesSegment(string s) {
bool flag = true;
for(int i = 1; i < s.length(); i++) {
if(s[i] == '0')
flag = false;
else if(s[i] == '1' && !flag)
return false;
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/07/PS/LeetCode/check-if-binary-string-has-at-most-one-segment-of-ones/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.