Skip to content

Latest commit

 

History

History
166 lines (125 loc) · 4.87 KB

2309.md

File metadata and controls

166 lines (125 loc) · 4.87 KB
title description keywords
2309. 兼具大小写的最好英文字母
LeetCode 2309. 兼具大小写的最好英文字母题解,Greatest English Letter in Upper and Lower Case,包含解题思路、复杂度分析以及完整的 JavaScript 代码实现。
LeetCode
2309. 兼具大小写的最好英文字母
兼具大小写的最好英文字母
Greatest English Letter in Upper and Lower Case
解题思路
哈希表
字符串
枚举

2309. 兼具大小写的最好英文字母

🟢 Easy  🔖  哈希表 字符串 枚举  🔗 力扣 LeetCode

题目

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 = "l** Ee** TcOd E "

Output: "E"

Explanation:

The letter 'E' is the only letter to appear in both lower and upper case.

Example 2:

Input: s = "a** rR** AzFif"

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.

题目大意

给你一个由英文字母组成的字符串 s ,请你找出并返回 s 中的 最好 英文字母。返回的字母必须为大写形式。如果不存在满足条件的字母,则返回一个空字符串。

最好 英文字母的大写和小写形式必须 s 中出现。

英文字母 b 比另一个英文字母 a 更好 的前提是:英文字母表中,ba 出现。

示例 1:

输入: s = "l Ee TcOd E "

输出: "E"

解释:

字母 'E' 是唯一一个大写和小写形式都出现的字母。

示例 2:

输入: s = "a rR AzFif"

输出: "R"

解释:

字母 'R' 是大写和小写形式都出现的最好英文字母。

注意 'A' 和 'F' 的大写和小写形式也都出现了,但是 'R' 比 'F' 和 'A' 更好。

示例 3:

输入: s = "AbCdEfGhIjK"

输出: ""

解释:

不存在大写和小写形式都出现的字母。

提示:

  • 1 <= s.length <= 1000
  • s 由小写和大写英文字母组成

解题思路

  1. 初始化数据结构

    • 使用一个 Set 存储字符串中出现的所有字符,方便快速检查字符是否存在。
  2. 遍历字符集合

    • 遍历集合中的每个字符。
    • 判断当前字符是否是大写字母(ASCII 码小于 91)。
    • 检查该大写字母对应的小写字母是否也存在于集合中。
  3. 更新结果

    • 如果满足上述条件,并且当前字符比结果 res 更大,则更新结果为当前字符。
  4. 返回结果

    • 遍历完成后,返回结果 res

复杂度分析

  • 时间复杂度O(n)

    • 构建集合:O(n),其中 n 是字符串长度。
    • 遍历集合:O(m),其中 m 是集合的大小(最多为 26 个字母)。
    • 总时间复杂度:O(n)
  • 空间复杂度O(n),使用了一个集合存储字符。

代码

/**
 * @param {string} s
 * @return {string}
 */
var greatestLetter = function (s) {
	const set = new Set([...s]);
	let res = '';
	for (let char of [...set]) {
		if (char.charCodeAt() < 91 && set.has(char.toLowerCase()) && char > res) {
			res = char;
		}
	}
	return res;
};

相关题目

题号 标题 题解 标签 难度 力扣
3120 统计特殊字母的数量 I 哈希表 字符串 🟢 🀄️ 🔗
3121 统计特殊字母的数量 II 哈希表 字符串 🟠 🀄️ 🔗