[LeetCode] Plates Between Candles

2055. Plates Between Candles

There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters ‘‘ and ‘|’ only, where a ‘‘ represents a plate and a ‘|’ represents a candle.

You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti…righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.

  • For example, s = “|||||“, and a query [3, 8] denotes the substring “||**|”. The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.

Return an integer array answer where answer[i] is the answer to the ith query.

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
class Solution {
public:
vector<int> platesBetweenCandles(string s, vector<vector<int>>& queries) {
int left, right;
for(left = 0; left < s.length() and s[left] == '*'; left++) {}
for(right = s.length() - 1; right >= 0 and s[right] == '*'; right--) {}
if(left >= right) return vector<int>(queries.size());

map<int, int> table;
vector<int> sum{0}, res;
int count = 0;
for(int i = left; i <= right; i++) {
if(s[i] == '|') {
sum.push_back(count);
table[i] = sum.size() - 1;
count = 0;
} else {
count++;
}
}

if(s[s.length() - 1] == '*') {
sum.push_back(0);
table[s.length()] = sum.size() - 1;
}

for(int i = 1; i < sum.size(); i++) {
sum[i] += sum[i-1];
}

for(auto& q : queries) {
if(sum.size() >= 3) {
auto l = table.lower_bound(q[0])->second;
auto r = prev(table.upper_bound(q[1]))->second;
if (r >= l) res.push_back(sum[r] - sum[l]);
else res.push_back(0);
} else res.push_back(0);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/30/PS/LeetCode/plates-between-candles/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.