You are given a 0-indexed string hamsters where hamsters[i] is either:
'H' indicating that there is a hamster at index i, or
'.' indicating that index i is empty.
You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index i can be fed if you place a food bucket at index i - 1and/or at index i + 1.
Return _the minimum number of food buckets you shouldplace at empty indices to feed all the hamsters or _-1if it is impossible to feed all of them.

Input: hamsters ="H..H"Output: 2Explanation: We place two food buckets at indices 1 and 2.It can be shown that if we place only one food bucket, one of the hamsters will not be fed.

Input: hamsters =".HHH."Output: -1Explanation: If we place a food bucket at every empty index as shown, the hamster at index 2 will not be able to eat.
To minimize buckets, we should place a bucket to the right of each hamster if possible, otherwise to the left. If neither is possible, it’s impossible to feed all hamsters.
classSolution {
funminimumBuckets(hamsters: String): Int {
val n = hamsters.length
val bucket = BooleanArray(n)
var ans = 0for (i in0 until n) {
if (hamsters[i] =='H') {
if (i+1 < n && hamsters[i+1] =='.'&& !bucket[i+1]) {
bucket[i+1] = true ans++ } elseif (i-1>=0&& hamsters[i-1] =='.'&& !bucket[i-1]) {
bucket[i-1] = true ans++ } else {
return -1 }
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defminimumBuckets(self, hamsters: str) -> int:
n: int = len(hamsters)
bucket: list[bool] = [False] * n
ans: int =0for i in range(n):
if hamsters[i] =='H':
if i+1< n and hamsters[i+1] =='.'andnot bucket[i+1]:
bucket[i+1] =True ans +=1elif i-1>=0and hamsters[i-1] =='.'andnot bucket[i-1]:
bucket[i-1] =True ans +=1else:
return-1return ans
impl Solution {
pubfnminimum_buckets(hamsters: String) -> i32 {
let n = hamsters.len();
letmut bucket =vec![false; n];
letmut ans =0;
let bytes = hamsters.as_bytes();
for i in0..n {
if bytes[i] ==b'H' {
if i+1< n && bytes[i+1] ==b'.'&&!bucket[i+1] {
bucket[i+1] =true;
ans +=1;
} elseif i >0&& bytes[i-1] ==b'.'&&!bucket[i-1] {
bucket[i-1] =true;
ans +=1;
} else {
return-1;
}
}
}
ans
}
}