Count Asterisks: 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 <= 1000sconsists of lowercase English letters, vertical bars'|', and asterisks'*'.scontains an even number of vertical bars'|'.
Solution
Explanation
Parse the input, if currently met odd bars, we count *.
Complexity
Time O(n)
Space O(1)
Java
public int countAsterisks(String s) {
int res = 0, bars = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '*' && bars % 2 == 0)
res++;
if (s.charAt(i) == '|')
bars++;
}
return res;
}
C++
int countAsterisks(string s) {
int res = 0, sign = 1;
for (char& c : s)
if ((sign ^= c == '|') && c == '*')
res++;
return res;
}
Python
Space O(n)
def countAsterisks(self, s: str) -> int:
return sum([a.count('*') for a in s.split('|')][0::2])Happy Learning – If you require any further information, feel free to contact me.
![[Solved] Count Asterisks LeetCode Contest Problem [Solved] Count Asterisks LeetCode Contest Problem](https://realcoder.techss24.com/wp-content/uploads/2022/06/Solved-Count-Asterisks-LeetCode-Contest-Problem.png)
![[Solved] Maximum XOR After Operations LeetCode Contest Problem](https://realcoder.techss24.com/wp-content/uploads/2022/06/Solved-Maximum-XOR-After-Operations-LeetCode-Contest-Problem-300x200.png)
![[Solved] Count Number of Bad Pairs LeetCode Contest](https://realcoder.techss24.com/wp-content/uploads/2022/08/Solved-Count-Number-of-Bad-Pairs-LeetCode-Contest-300x200.png)
![[Solved] Largest Local Values in a Matrix LeetCode Contest Problem](https://realcoder.techss24.com/wp-content/uploads/2022/08/Solved-Largest-Local-Values-in-a-Matrix-LeetCode-Contest-Problem-300x200.png)