[LeetCode] Count Houses in a Circular Street II

2753. Count Houses in a Circular Street II

You are given an object street of class Street``k which represents a maximum bound for the number of houses in that street (in other words, the number of houses is less than or equal to k). Houses’ doors could be open or closed initially (at least one is open).

Initially, you are standing in front of a door to a house on this street. Your task is to count the number of houses in the street.

The class Street contains the following functions which may help you:

  • void closeDoor(): Close the door of the house you are in front of.
  • boolean isDoorOpen(): Returns true if the door of the current house is open and false otherwise.
  • void moveRight(): Move to the right house.

1 to n, then the right house of housei is housei+1 for i < n, and the right house of housen is house1.

Return ans which represents the number of houses on this street.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for a street.
* class Street {
* public:
* Street(vector<int> doors);
* void closeDoor();
* bool isDoorOpen();
* void moveRight();
* };
*/
class Solution {
public:
int houseCount(Street* street, int k) {
vector<int> o(2 * k), p(2 * k);
for(int i = 0; i < 2 * k; i++) {
o[i] = street->isDoorOpen();
street->moveRight();
}
while(!street->isDoorOpen()) street->moveRight();
street->closeDoor();
street->moveRight();
for(int i = 0; i < 2 * k; i++) {
p[i] = street->isDoorOpen();
street->moveRight();
}
vector<int> PI(2 * k);
for(int i = 1, j = 0; i < p.size(); i++) {
while(j and p[i] != p[j]) j = PI[j-1];
if(p[i] == p[j]) PI[i] = ++j;
}
int res = 0;
for(int i = 0, j = 0; i < p.size(); i++) {
while(j and o[i] != p[j]) j = PI[j-1];
if(o[i] == p[j]) {
j += 1;
res = max(res, j);
if(j == p.size()) j = PI[j-1];
}
}
return res + 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/06/30/PS/LeetCode/count-houses-in-a-circular-street-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.