carloscn / structstudy

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

leetcode2068: Check Whether Two Strings are Almost Equivalent #333

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3.

Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise.

The frequency of a letter x is the number of times it occurs in the string.

Example 1:

Input: word1 = "aaaa", word2 = "bccb" Output: false Explanation: There are 4 'a's in "aaaa" but 0 'a's in "bccb". The difference is 4, which is more than the allowed 3.

Example 2:

Input: word1 = "abcdeef", word2 = "abaaacc" Output: true Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:

Example 3:

Input: word1 = "cccddabba", word2 = "babababab" Output: true Explanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:

Constraints:

n == word1.length == word2.length 1 <= n <= 100 word1 and word2 consist only of lowercase English letters.

carloscn commented 1 year ago

Analysis

int32_t check_almost_equivalent(const char *word1, const char *word2, bool *result)
{
    int32_t ret = 0;
    size_t w1_len, w2_len;

    UTILS_CHECK_PTR(word1);
    UTILS_CHECK_PTR(word2);
    UTILS_CHECK_PTR(result);
    UTILS_CHECK_LEN(w1_len = strlen(word1));
    UTILS_CHECK_LEN(w2_len = strlen(word2));

    int32_t w1_rom[26] = {0};
    int32_t w2_rom[26] = {0};
    size_t max_len = (w1_len > w2_len)?w1_len:w2_len;

    for (size_t i = 0; i < max_len; i ++) {
        if (i < w1_len) {
            w1_rom[(size_t)(word1[i] - 'a')] ++;
        }

        if (i < w2_len) {
            w2_rom[(size_t)(word2[i] - 'a')] ++;
        }
    }

    for (size_t i = 0; i < 26; i ++) {
        if (utils_int32_abs(w1_rom[i] - w2_rom[i]) > 3) {
            *result = false;
            goto finish;
        }
    }

    *result = true;

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168672 https://github.com/carloscn/structstudy/commit/b266303597c1e2d8eafa3f7c9eab7d61dde8996b