1603. Design Parking System leetcode solution in c++
class ParkingSystem {
private:
int bigSlots;
int mediumSlots;
int smallSlots;
public:
ParkingSystem(int big, int medium, int small) {
bigSlots = big;
mediumSlots = medium;
smallSlots = small;
}
bool addCar(int carType) {
if (carType == 1 && bigSlots > 0) {
bigSlots--;
return true;
}
if (carType == 2 && mediumSlots > 0) {
mediumSlots--;
return true;
}
if (carType == 3 && smallSlots > 0) {
smallSlots--;
return true;
}
return false;
}
};
The above code is a solution to the "Design Parking System" problem on LeetCode. The problem requires us to design a parking system that has a certain number of parking slots for different car types (big, medium, and small) and check if a car of a given type can be parked.
Class and Constructor
The code defines a class called ParkingSystem
. It has three private member variables: bigSlots
, mediumSlots
, and smallSlots
, which represent the number of available parking slots for each car type.
The constructor ParkingSystem(int big, int medium, int small)
is used to initialize the parking system with the given number of slots for each car type. The constructor takes three parameters: big
, medium
, and small
, which represent the number of available slots for each car type.
Method: addCar
The addCar
method is used to check if a car of a given type can be parked in the parking system. It takes an integer parameter carType
that represents the type of the car (1 for big, 2 for medium, and 3 for small).
The method first checks if the carType
is 1 (big) and if there are available big slots (bigSlots > 0
). If both conditions are true, it decrements the bigSlots
count and returns true
to indicate that the car can be parked.
If the carType
is not 1, it checks if it is 2 (medium) and if there are available medium slots (mediumSlots > 0
). If both conditions are true, it decrements the mediumSlots
count and returns true
.
If the carType
is not 1 or 2, it checks if it is 3 (small) and if there are available small slots (smallSlots > 0
). If both conditions are true, it decrements the smallSlots
count and returns true
.
If none of the above conditions are met, it means there are no available slots for the given car type, so it returns false
to indicate that the car cannot be parked.
Summary
The code defines a ParkingSystem
class with a constructor to initialize the number of parking slots for each car type. It provides a method addCar
to check if a car of a given type can be parked, based on the availability of slots for that type. The code uses simple if-else conditions to determine the availability of slots and decrements the respective slot count if a car can be parked.