2309. Greatest English Letter in Upper and Lower Case — Daily Problem
2309. Greatest English Letter in Upper and Lower Case
Approach
- Hash table: The first approach that comes to mind is using a dictionary. But it turns out we can directly traverse the alphabet from
Zdownward, check if both cases exist, and return immediately.
Runtime beats 99.9%
- Bit manipulation: We use two integers
mask1andmask2to record which lowercase and uppercase letters appear in strings. Inmask1, bitirepresents whether lowercase letteriappears; inmask2, bitirepresents whether uppercase letteriappears.
We then perform a bitwise AND of mask1 and mask2. The result mask has bit i set only if both cases of letter i appear.
We find the highest set bit in mask and convert it to the corresponding uppercase letter. If no bit is set, return an empty string.
Author: ylb
Link: https://leetcode.cn/problems/greatest-english-letter-in-upper-and-lower-case/solutions/2077636/by-lcbin-zbg0/
Source: LeetCode
All rights reserved by the author. Commercial use requires authorization; non-commercial use must cite the source.
Code
class Solution:
def greatestLetter(self, s: str) -> str:
for i in range(90, 64, -1):
if chr(i) in s and chr(i+32) in s:
return chr(i)
return ""class Solution {
public:
string greatestLetter(string s) {
unordered_set<char> strin(s.begin(),s.end());
for(char c = 'Z'; c >= 'A'; --c){
if(strin.count(c) && strin.count(char(c+32))){
return string(1,c);
}
}
return "";
}
};class Solution:
def greatestLetter(self, s: str) -> str:
# Use two integers mask1 and mask2 to record lowercase and uppercase letters in s
# In mask1, bit i represents whether lowercase letter i appears;
# In mask2, bit i represents whether uppercase letter i appears.
mask1 = mask2 = 0
for i in s:
if i.islower():
mask1 |= 1 << (ord(i) - ord("a"))
else:
mask2 |= 1 << (ord(i) - ord("A"))
mask = mask1 & mask2
return chr(mask.bit_length() - 1 + ord("A")) if mask else ""贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
One question daily 2299. Code inspection device II
LeetCode 2299. 强密码检验器 II 题解 — 模拟与位运算检查密码强度,使用掩码 mask 记录是否包含小写字母、大写字母、数字和特殊字符,并确保无连续相同字符。适合刷题求职者、准备算法面试的 CS 学生。
2309. The best English letters with both appropriates and lowercases One question daily
LeetCode 2309. 兼具大小写的最好英文字母 题解 — 使用哈希表与位运算两种解法,哈希表法从 Z 开始逆序查找字母是否同时出现大小写,位运算法用两个整数掩码分别记录小写和大写字母出现情况,再通过与运算找出最高位对应字母。适合正在刷 LeetCode 每日一题、想掌握哈希表与位运算技巧的求职者和算法学习者。