
LeetCode 1784 – Check if Binary String Has at Most One Segment of Ones (Day-06)
A very interesting string observation problem from LeetCode that can be solved in one line using find() in C++. Problem You are given a binary string s without leading zeros . Return true if the string contains at most one contiguous segment of '1's , otherwise return false . Example Input: "1001" Output: false Explanation: 1 000 1 There are two segments of ones , so the answer is false . Another example: Input: "11100" Output: true There is only one segment of ones . Key Observation If a binary string has more than one segment of ones , there must be a pattern: 01 Why? Because after the first segment of 1 s ends, we see: 1 → 0 And when another 1 starts again, the string must contain: 01 Example: 1001 ↑ "01" So the trick is simple: If "01" exists in the string, then there are multiple segments of ones . 3 Elegant One-Line Solution class Solution { public: bool checkOnesSegment ( string s ) { return s . find ( "01" ) == string :: npos ; } }; Explanation string::npos means pattern not fo
Continue reading on Dev.to
Opens in a new tab

