carloscn / structstudy

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

leetcode2309: Greatest English Letter in Upper and Lower Case #379

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string.

An English letter b is greater than another letter a if b appears after a in the English alphabet.

Example 1:

Input: s = "lEeTcOdE" Output: "E" Explanation: The letter 'E' is the only letter to appear in both lower and upper case.

Example 2:

Input: s = "arRAzFif" Output: "R" Explanation: The letter 'R' is the greatest letter to appear in both lower and upper case. Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.

Example 3:

Input: s = "AbCdEfGhIjK" Output: "" Explanation: There is no letter that appears in both lower and upper case.

Constraints:

1 <= s.length <= 1000 s consists of lowercase and uppercase English letters.

carloscn commented 1 year ago

Analysis

static int32_t greatest_letter(char *s)
{
    int32_t ret = 0;
    size_t len;

    UTILS_CHECK_PTR(s);
    UTILS_CHECK_LEN(len = strlen(s));
    char max = '\0';
    for (size_t i = 0; i < len; i ++) {
        char e = s[i];
        int8_t f = isupper(e)? 1: -1;
        for (size_t j = i + 1; j < len; j ++) {
            char m = s[j];
            if ((int8_t)m == ((int8_t)32 * f + (int8_t)e)) {
                char M = utils_conv_uppercase(m);
                max = max > M ? max : M;
            }
        }
    }

    s[0] = max;
    s[1] = '\0';

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170633 https://github.com/carloscn/structstudy/commit/acdbd95c6bc5597dfc4ff165a628492b686e06e3