You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.
Return the number of '*' in s, excluding the '*' between each pair of '|'.
Note that each '|' will belong to exactly one pair.
Example 1:
Input: s = "l|*e*et|c**o|*de|" Output: 2 Explanation: The considered characters are underlined: "l|*e*et|c**o|*de|". The characters between the first and second '|' are excluded from the answer. Also, the characters between the third and fourth '|' are excluded from the answer. There are 2 asterisks considered. Therefore, we return 2.
Example 2:
Input: s = "iamprogrammer" Output: 0 Explanation: In this example, there are no asterisks in s. Therefore, we return 0.
Example 3:
Input: s = "yo|uar|e**|b|e***au|tifu|l" Output: 5 Explanation: The considered characters are underlined: "yo|uar|e**|b|e***au|tifu|l". There are 5 asterisks considered. Therefore, we return 5.
Constraints:
1 <= s.length <= 1000s consists of lowercase English letters, vertical bars '|', and asterisks '*'.s contains an even number of vertical bars '|'.This approach involves a pass through the string while maintaining a boolean flag to keep track of whether you are inside or outside of a vertical bar pair. You increment the asterisk count only when the flag indicates that you are outside of such a pair.
This C solution uses a simple loop over the string s. The variable inside_bar toggles between 0 and 1 when a '|' is encountered to indicate entry and exit from a pair. Asterisks are counted only when inside_bar is 0.
C++
Java
Python
C#
JavaScript
Time complexity: O(n), where n is the length of the string.
Space complexity: O(1), since no additional space is used except for counters.
This alternative approach is to use regular expressions to clean out the sections of the string found between the vertical bar pairs and then simply count asterisks in the resulting string.
This Python solution uses the re.sub method to substitute all characters between '|' pairs with an empty string, effectively removing them, and then uses count to find remaining asterisks.
JavaScript
Time complexity: O(n), where n represents the input string length.
Space complexity: O(n) due to the construction of the intermediate cleaned string.
| Approach | Complexity |
|---|---|
| Toggle Counting Using a Boolean Flag | Time complexity: O(n), where n is the length of the string. |
| Use Regular Expression for Pattern Matching | Time complexity: O(n), where n represents the input string length. |
2315. Count Asterisks | LEETCODE EASY • code Explainer • 991 views views
Watch 9 more video solutions →Practice Count Asterisks with our built-in code editor and test cases.
Practice on FleetCode