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'*'ins _,excluding the _'*'between each pair of'|'.
Note that each '|' will belong to exactly one pair.
Input: s ="l|*e*et|c**o|*de|"Output: 2Explanation: 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 return2.
Input: s ="yo|uar|e**|b|e***au|tifu|l"Output: 5Explanation: The considered characters are underlined:"_yo_ |uar|_e**_ |b|_e***au_ |tifu|_l_ ". There are 5 asterisks considered. Therefore, we return5.
We can keep a flag to track whether we are inside a pair of vertical bars. We only count ‘*’ when we are outside any such pair. Every time we see a ‘|’, we toggle the flag.
classSolution {
publicintcountAsterisks(String s) {
int ans = 0;
boolean inside =false;
for (char c : s.toCharArray()) {
if (c =='|') inside =!inside;
elseif (c =='*'&&!inside) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funcountAsterisks(s: String): Int {
var ans = 0var inside = falsefor (c in s) {
if (c =='|') inside = !inside
elseif (c =='*'&&!inside) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defcountAsterisks(self, s: str) -> int:
ans =0 inside =Falsefor c in s:
if c =='|':
inside =not inside
elif c =='*'andnot inside:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfncount_asterisks(s: String) -> i32 {
letmut ans =0;
letmut inside =false;
for c in s.chars() {
if c =='|' {
inside =!inside;
} elseif c =='*'&&!inside {
ans +=1;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
countAsterisks(s: string):number {
letans=0, inside=false;
for (constcofs) {
if (c==='|') inside=!inside;
elseif (c==='*'&&!inside) ans++;
}
returnans;
}
}