---
# System prepended metadata

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

---

# LeetCode 1784. Check if Binary String Has at Most One Segment of Ones
[LeetCode 1784. Check if Binary String Has at Most One Segment of Ones](https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/) (<font color=#00AF9B>Easy</font> 39.2%) 
<!-- 
(<font color=#00AF9B>Easy</font> 53.8%) 
(<font color=#FFB800>Medium</font> 39.6%)
(<font color=#FF375F>Hard</font>)
 -->
    
- 限制 :

    <ul>
    <li><code>1 <= s.length <= 100</code></li>
    <li><code>s[i] is either '0' or '1'.</code></li>
    <li><code>s[0] is '1'.</code></li>
    </ul>

- Solution
    這題要找的是1有沒有都在字串的前面，如果沒有就回傳 false。
    - 時間複雜度: $O(n)$
    - 空間複雜度: $O(1)$

- 程式碼
    ```c++=
    class Solution {
    public:
        bool checkOnesSegment(string s) {
            char nowChr = '1';
            for (auto& chr : s) {
                if (chr == '0') {
                    nowChr = chr;
                    continue;
                }
                if (chr != nowChr)
                    return false;
            }
            return true;
        }
    };
    ```
</details>