1784. Check if Binary String Has at Most One Segment of Ones
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, setfoundOne
to true. - If the current character is '0' and
foundOne
is true, resetfoundOne
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)
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.