Problem Description
Given a string s, count the number of asterisks '*' that are not between paired vertical bars '|'. The vertical bars come in pairs (first with second, third with fourth, etc.), and any asterisks between a pair are ignored.
Key Insights
- Use a flag to keep track of whether you are inside a pair of vertical bars.
- Iterate through the string once, toggling the flag every time you encounter a '|'.
- Count asterisks only when the flag indicates you are outside of any paired vertical bars.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s. Space Complexity: O(1), as only a few variables are used regardless of input size.
Solution
We solve the problem by iterating through the string and maintaining a boolean variable that indicates if we are inside a pair of vertical bars. Every time we see a '|', we flip the state of the flag. If the current character is an asterisk '*' and the flag is false (indicating we are outside a paired region), we increment our counter. This simple iteration makes the solution both efficient and easy to understand.