Count Asterisks
Problem
You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair (the 1st and 2nd bars are a pair, the 3rd and 4th are a pair, and so on). Return the number of '*' characters in s, excluding the asterisks that lie between any pair of '|'. The number of bars is guaranteed to be even.
s = "l|*e*et|c**o|*de|"2def count_asterisks(s):
inside = False
count = 0
for ch in s:
if ch == "|":
inside = not inside
elif ch == "*" and not inside:
count += 1
return count
function countAsterisks(s) {
let inside = false;
let count = 0;
for (const ch of s) {
if (ch === "|") {
inside = !inside;
} else if (ch === "*" && !inside) {
count++;
}
}
return count;
}
class Solution {
public int countAsterisks(String s) {
boolean inside = false;
int count = 0;
for (char ch : s.toCharArray()) {
if (ch == '|') inside = !inside;
else if (ch == '*' && !inside) count++;
}
return count;
}
}
int countAsterisks(string s) {
bool inside = false;
int count = 0;
for (char ch : s) {
if (ch == '|') inside = !inside;
else if (ch == '*' && !inside) count++;
}
return count;
}
Explanation
The vertical bars split the string into alternating regions: outside a pair, then inside a pair, then outside again, and so on. We only want to count asterisks in the outside regions.
A single boolean inside tracks which kind of region we are currently in. It starts false (we begin outside any pair).
Every time we hit a '|' we flip the flag: the first bar opens a pair (we go inside), the second bar closes it (we go back outside), and the pattern repeats. We never need to match bars explicitly — the toggle does it.
For any '*' we check the flag: if inside is false the star is in an open region, so we increment count; if inside is true we skip it. All other characters are irrelevant. One pass, constant extra space.
Example: "l|*e*et|c**o|*de|". The first | turns us inside, so the two stars in *e*et are skipped. The next | turns us outside, so both stars in c**o count. The last pair encloses *de, skipping its star. Total = 2.