Skip to content

Latest commit

 

History

History

2309

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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.

Companies: Microsoft

Related Topics:
Hash Table, String, Enumeration

Solution 1.

// OJ: https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    string greatestLetter(string s) {
        char ans = 0;
        int seen[26] = {};
        for (char c : s) {
            int lower = !!islower(c), i = lower ? c - 'a' : c - 'A';
            seen[i] |= 1 << lower;
            if (seen[i] == 3 && 'A' + i > ans) ans = 'A' + i;
        }
        return ans ? string(1, ans) : "";
    }
};