You are given a string s
that contains some characters and/or asterisks ('*'
). You are required to count the number of asterisks ('*'
) that are not enclosed between pairs of pipe ('|'
) characters.
More formally, the asterisks to be counted are not:
|
that contains zero or more pipe characters.Example:
s = "l|*e*et|c**o|*de|"
2
s
contain?
|
should be taken into account.s
is non-empty.|
pairs).s
, as we need to traverse the entire string once.Here’s the Python code to solve the problem:
def countAsterisks(s: str) -> int:
inside_pipes = False
asterisk_count = 0
for char in s:
if char == '|':
inside_pipes = not inside_pipes
elif char == '*' and not inside_pipes:
asterisk_count += 1
return asterisk_count
# Example usage:
s = "l|*e*et|c**o|*de|"
print(countAsterisks(s)) # Output: 2
This implementation correctly counts the number of asterisks that are not enclosed between any pairs of pipe characters.
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?