carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2315: Count Asterisks #380

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

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|eet|c*o|de|" Output: 2 Explanation: The considered characters are underlined: "l|eet|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|eau|tifu|l" Output: 5 Explanation: The considered characters are underlined: "yo|uar|e|b|eau|tifu|l". There are 5 asterisks considered. Therefore, we return 5.

Constraints:

1 <= s.length <= 1000 s consists of lowercase English letters, vertical bars '|', and asterisks '*'. s contains an even number of vertical bars '|'.

carloscn commented 11 months ago

Analysis

pub fn count_asterisks(s: &str) -> i32
{
    let mut ret:i32 = 0;
    if s.len() < 1 {
        return ret;
    }

    let mut i:usize = 0;
    let s_vec:Vec<&str> = s.split('|').into_iter().collect();

    while i < s_vec.len() {
        i += 1;
        if (i & 0x1) == 0 {
            continue;
        }
        let e = s_vec[i - 1];
        ret += e.chars().fold(0, |mut count, x| {
            if x == '*' {
                count += 1;
            }
            count
        });
    }

    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170674 https://github.com/carloscn/structstudy/commit/fd4521b710f53230d40326a90d17722949977508