|
| 1 | +// Source : https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-05-30 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer |
| 8 | + * than the longest contiguous segment of 0s in s. Return false otherwise. |
| 9 | + * |
| 10 | + * For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the |
| 11 | + * longest contiguous segment of 0s has length 3. |
| 12 | + * |
| 13 | + * Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have |
| 14 | + * length 0. The same applies if there are no 1s. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * |
| 18 | + * Input: s = "1101" |
| 19 | + * Output: true |
| 20 | + * Explanation: |
| 21 | + * The longest contiguous segment of 1s has length 2: "1101" |
| 22 | + * The longest contiguous segment of 0s has length 1: "1101" |
| 23 | + * The segment of 1s is longer, so return true. |
| 24 | + * |
| 25 | + * Example 2: |
| 26 | + * |
| 27 | + * Input: s = "111000" |
| 28 | + * Output: false |
| 29 | + * Explanation: |
| 30 | + * The longest contiguous segment of 1s has length 3: "111000" |
| 31 | + * The longest contiguous segment of 0s has length 3: "111000" |
| 32 | + * The segment of 1s is not longer, so return false. |
| 33 | + * |
| 34 | + * Example 3: |
| 35 | + * |
| 36 | + * Input: s = "110100010" |
| 37 | + * Output: false |
| 38 | + * Explanation: |
| 39 | + * The longest contiguous segment of 1s has length 2: "110100010" |
| 40 | + * The longest contiguous segment of 0s has length 3: "110100010" |
| 41 | + * The segment of 1s is not longer, so return false. |
| 42 | + * |
| 43 | + * Constraints: |
| 44 | + * |
| 45 | + * 1 <= s.length <= 100 |
| 46 | + * s[i] is either '0' or '1'. |
| 47 | + ******************************************************************************************************/ |
| 48 | + |
| 49 | +class Solution { |
| 50 | +public: |
| 51 | + bool checkZeroOnes(string s) { |
| 52 | + int zeros = 0; |
| 53 | + int ones = 0; |
| 54 | + int i = 0; |
| 55 | + while (i < s.size()) { |
| 56 | + if(s[i] == '0') { |
| 57 | + int cnt = 0; |
| 58 | + for (;s[i] == '0' && i < s.size(); i++) cnt++; |
| 59 | + zeros = max(zeros, cnt); |
| 60 | + }else { |
| 61 | + int cnt = 0; |
| 62 | + for (;s[i] == '1'&& i < s.size(); i++) cnt++; |
| 63 | + ones = max(ones, cnt); |
| 64 | + } |
| 65 | + } |
| 66 | + return ones > zeros; |
| 67 | + } |
| 68 | +}; |
0 commit comments