Leetcode 2315. Count Asterisks
You are given a string s
, which contains |
(pipe) and *
(asterisk) characters. We want to determine the number of asterisks in the string that are not enclosed between pairs of pipe characters.
A pair of pipe characters is considered to enclose everything between them if there is an even number of |
characters. For example, in the string "|**|*|**|"
, only the first two and the last asterisk are enclosed by a pair of pipes.
s
?
|
and *
?
|
and *
.|
. Toggle the inside-pipes flag.*
) and we are not inside a pair of pipes, increment the asterisk counter.*
.#include <iostream>
#include <string>
int countAsterisks(std::string s) {
int asteriskCount = 0;
bool insidePipes = false;
for (char c : s) {
if (c == '|') {
insidePipes = !insidePipes;
} else if (c == '*' && !insidePipes) {
asteriskCount++;
}
}
return asteriskCount;
}
int main() {
std::string s = "l|*e*et|c**o|*de|";
std::cout << "Count of asterisks not enclosed by pipes: " << countAsterisks(s) << std::endl;
return 0;
}
s
. We only make a single pass through the string, checking each character.This solution ensures that we count only the asterisks that are outside of any pipe-enclosed section efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?