carloscn / structstudy

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

leetcode2278: Percentage of Letter in String #373

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.

Example 1:

Input: s = "foobar", letter = "o" Output: 33 Explanation: The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.

Example 2:

Input: s = "jjjj", letter = "k" Output: 0 Explanation: The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.

Constraints:

1 <= s.length <= 100 s consists of lowercase English letters. letter is a lowercase English letter.

carloscn commented 1 year ago

Analysis

static int32_t percentage_letter(const char *s, char letter)
{
    int32_t ret = -1;
    size_t len;

    UTILS_CHECK_PTR(s);
    UTILS_CHECK_LEN(len = strlen(s));

    int32_t count = 0;
    for (size_t i = 0; i < len; i ++) {
        if (s[i] == letter) {
            count ++;
        }
    }

    ret = count * 100 / len;

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170463 https://github.com/carloscn/structstudy/commit/a93e838defbdd43b73a58d6b5348dee09d1e459d