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

Master LeetCode problem 1784 (Check if Binary String Has at Most One Segment of Ones), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

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

Easy

Problem Explanation

Explanation

To solve this problem, we can iterate through the binary string and check if there is more than one segment of ones. We can maintain a flag to track if we have seen a one and if we see another one, we can set the flag to false. If we encounter a zero after seeing a one, we can reset the flag. If the flag is false and we encounter another one, then there are more than one segment of ones.

  • Initialize a boolean flag foundOne to false.
  • Iterate through the binary string.
  • If the current character is '1', check if foundOne is already true. If true, return false as there are more than one segment of ones. Otherwise, set foundOne to true.
  • If the current character is '0' and foundOne is true, reset foundOne to false.
  • If the loop finishes without any issues, return true as there is at most one segment of ones.

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1)

Solution Code

class Solution {
    public boolean checkOnesSegment(String s) {
        boolean foundOne = false;
        for (char c : s.toCharArray()) {
            if (c == '1') {
                if (foundOne) {
                    return false;
                }
                foundOne = true;
            } else if (foundOne) {
                foundOne = false;
            }
        }
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1784 (Check if Binary String Has at Most One Segment of Ones)?

This page provides optimized solutions for LeetCode problem 1784 (Check if Binary String Has at Most One Segment of Ones) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1784 (Check if Binary String Has at Most One Segment of Ones)?

The time complexity for LeetCode 1784 (Check if Binary String Has at Most One Segment of Ones) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1784 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1784 in Java, C++, or Python.

Back to LeetCode Solutions