carloscn / structstudy

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

leetcode2283: Check if Number Has Equal Digit Count and Digit Value #374

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

You are given a 0-indexed string num of length n consisting of digits.

Return true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.

Example 1:

Input: num = "1210" Output: true Explanation: num[0] = '1'. The digit 0 occurs once in num. num[1] = '2'. The digit 1 occurs twice in num. num[2] = '1'. The digit 2 occurs once in num. num[3] = '0'. The digit 3 occurs zero times in num. The condition holds true for every index in "1210", so return true.

Example 2:

Input: num = "030" Output: false Explanation: num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num. num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num. num[2] = '0'. The digit 2 occurs zero times in num. The indices 0 and 1 both violate the condition, so return false.

Constraints:

n == num.length 1 <= n <= 10 num consists of digits.

carloscn commented 11 months ago

Analysis

static int32_t digit_count(const char *num, bool *result)
{
    int32_t ret = 0;
    size_t len;

    UTILS_CHECK_PTR(num);
    UTILS_CHECK_PTR(result);
    UTILS_CHECK_LEN(len = strlen(num));

    int32_t bucket[11] = {0};

    for (size_t i = 0; i < len; i ++) {
        bucket[(size_t)(num[i] - '0')] ++;
    }

    for (size_t i = 0; i < len; i ++) {
        if ((int32_t)(num[i] - '0') != bucket[i]) {
            *result = false;
            goto finish;
        }
    }

    *result = true;

finish:
    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170517 https://github.com/carloscn/structstudy/commit/36bba9eff9e092796d90768d301068f162f693a6