LeetCode 2222: Number of Ways to Select Buildings
Problem Description
Explanation:
To solve this problem, we can iterate through the binary string and count the number of ways to select 3 buildings that satisfy the given conditions. We can use a sliding window approach to keep track of the current selection of buildings. If the current selection violates the condition of having consecutive buildings of the same type, we can skip that selection.
- Initialize a counter variable to keep track of the number of valid selections.
- Use a sliding window of size 3 to iterate through the binary string.
- Check if the current selection violates the condition of having consecutive buildings of the same type. If it does not, increment the counter.
- Return the final count as the result.
Time Complexity: O(n), where n is the length of the binary string.
Space Complexity: O(1)
Solutions
class Solution {
public int numWays(String s) {
int count = 0;
for (int i = 0; i <= s.length() - 3; i++) {
if (s.charAt(i) != s.charAt(i + 1) && s.charAt(i + 1) != s.charAt(i + 2) && s.charAt(i) != s.charAt(i + 2)) {
count++;
}
}
return count;
}
}
Loading editor...