2315. Count Asterisks Easy

@problem@discussion
#String



1/**
2 * [2315] Count Asterisks
3 *
4 * You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1^st and 2^nd '|' make a pair, the 3^rd and 4^th '|' make a pair, and so forth.
5 * Return the number of '*' in s, excluding the '*' between each pair of '|'.
6 * Note that each '|' will belong to exactly one pair.
7 *  
8 * Example 1:
9 *
10 * Input: s = "l|*e*et|c**o|*de|"
11 * Output: 2
12 * Explanation: The considered characters are underlined: "<u>l</u>|*e*et|<u>c**o</u>|*de|".
13 * The characters between the first and second '|' are excluded from the answer.
14 * Also, the characters between the third and fourth '|' are excluded from the answer.
15 * There are 2 asterisks considered. Therefore, we return 2.
16 * Example 2:
17 *
18 * Input: s = "iamprogrammer"
19 * Output: 0
20 * Explanation: In this example, there are no asterisks in s. Therefore, we return 0.
21 *
22 * Example 3:
23 *
24 * Input: s = "yo|uar|e**|b|e***au|tifu|l"
25 * Output: 5
26 * Explanation: The considered characters are underlined: "<u>yo</u>|uar|<u>e**</u>|b|<u>e***au</u>|tifu|<u>l</u>". There are 5 asterisks considered. Therefore, we return 5.
27 *  
28 * Constraints:
29 *
30 * 1 <= s.length <= 1000
31 * s consists of lowercase English letters, vertical bars '|', and asterisks '*'.
32 * s contains an even number of vertical bars '|'.
33 *
34 */
35pub struct Solution {}
36
37// problem: https://leetcode.com/problems/count-asterisks/
38// discuss: https://leetcode.com/problems/count-asterisks/discuss/?currentPage=1&orderBy=most_votes&query=
39
40// submission codes start here
41
42impl Solution {
43    pub fn count_asterisks(s: String) -> i32 {
44        let (mut count, mut enable) = (0, true);
45
46        for c in s.chars() {
47            if enable && c == '*' {
48                count += 1;
49            }
50
51            if c == '|' {
52                enable = !enable;
53            }
54        }
55        count
56    }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_2315() {
67        assert_eq!(
68            Solution::count_asterisks("yo|uar|e**|b|e***au|tifu|l".to_string()),
69            5
70        );
71    }
72}
73


Back
© 2025 bowen.ge All Rights Reserved.