题目

地址

https://leetcode.com/problems/minimum-number-of-chairs-in-a-waiting-room/description/

内容

You are given a string s. Simulate events at each second i:

If s[i] == ‘E’, a person enters the waiting room and takes one of the chairs in it.
If s[i] == ‘L’, a person leaves the waiting room, freeing up a chair.
Return the minimum number of chairs needed so that a chair is available for every person who enters the waiting room given that it is initially empty.

Example 1:

Input: s = “EEEEEEE”
Output: 7
Explanation:
After each second, a person enters the waiting room and no person leaves it. Therefore, a minimum of 7 chairs is needed.

Example 2:

Input: s = “ELELEEL”
Output: 2
Explanation:
Let’s consider that there are 2 chairs in the waiting room. The table below shows the state of the waiting room at each second.

SecondEventPeople in the Waiting RoomAvailable Chairs
0Enter11
1Leave02
2Enter11
3Leave02
4Enter11
5Enter20
6Leave11

Example 3:

Input: s = “ELEELEELLL”
Output: 3
Explanation:
Let’s consider that there are 3 chairs in the waiting room. The table below shows the state of the waiting room at each second.

SecondEventPeople in the Waiting RoomAvailable Chairs
0Enter12
1Leave03
2Enter12
3Enter21
4Leave12
5Enter21
6Enter30
7Leave21
8Leave12
9Leave03

Constraints:

  • 1 <= s.length <= 50
  • s consists only of the letters ‘E’ and ‘L’.
  • s represents a valid sequence of entries and exits.

解题

这题就是模拟一个队列,E代表如队列,L代表出队列。然后按照字符串中的EL的信息,计算出这个队列最长时是多长。
我们不用使用队列或者栈这样的数据结构,直接使用计数器来做就行了。

#include <string>
#include <stack>
using namespace std;

class Solution {
public:
    int minimumChairs(string s) {
        int maxChairs = 0;
        stack<int> chairs;
        for (char c : s) {
            if (c == 'L') {
                chairs.pop();
            } else {
                chairs.push(1);
                maxChairs = max(maxChairs, (int)chairs.size());
            }
        }
        return maxChairs;
    }
};

在这里插入图片描述

代码地址

https://github.com/f304646673/leetcode/tree/main/3168-Minimum-Number-of-Chairs-in-a-Waiting-Room/cplusplus

更多推荐