「每日LeetCode」2021年4月8日

本文最后更新于:2023年3月19日 晚上

Lt1763. 最长的美好子字符串

1763. 最长的美好子字符串

当一个字符串 s 包含的每一种字母的大写和小写形式 同时 出现在 s 中,就称这个字符串 s美好 字符串。比方说,"abABB" 是美好字符串,因为 'A''a' 同时出现了,且 'B''b' 也同时出现了。然而,"abA" 不是美好字符串因为 'b' 出现了,而 'B' 没有出现。
给你一个字符串 s ,请你返回 s 最长的 美好子字符串 。如果有多个答案,请你返回 最早 出现的一个。如果不存在美好子字符串,请你返回一个空字符串。

示例 1:

1
2
3
4
输入:s = "YazaAay"
输出:"aAa"
解释:"aAa" 是一个美好字符串,因为这个子串中仅含一种字母,其小写形式 'a' 和大写形式 'A' 也同时出现了。
"aAa" 是最长的美好子字符串。

示例 2:

1
2
3
输入:s = "Bb"
输出:"Bb"
解释:"Bb" 是美好字符串,因为 'B'和 'b' 都出现了。整个字符串也是原字符串的子字符串。

示例 3:

1
2
3
输入:s = "c"
输出:""
解释:没有美好子字符串。

示例 4:

1
2
3
4
输入:s = "dDzeE"
输出:"dD"
解释:"dD""eE" 都是最长美好子字符串。
由于有多个美好子字符串,返回 "dD" ,因为它出现得最早。

提示:

  • 1 <= s.length <= 100
  • s 只包含大写和小写英文字母。

思路

暴力解。通过 set 来判断这个子串是不是美好字符串,得到 asc 码,计算出对应的大写或者小写字符,判断 set 中是否有这个元素,没有的话返回 false,有的话删除两个元素后继续判断。外层中,遍历每一个子串,如果当前子串长度比最大子串小,直接剪枝。比当前子串大且是美好子串就更新最大子串,最后返回最大子串。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* @param {string} s
* @return {string}
*/
var longestNiceSubstring = function (s) {
let max = "";

const isNice = (str) => {
if (str.length < 2) return false;
const set = new Set(str.split(""));
for (const char of set.values()) {
const code = char.charCodeAt();
const targetChar =
code < 97
? String.fromCharCode(code + 32)
: String.fromCharCode(code - 32);
if (!set.has(targetChar)) return false;
else {
set.delete(char);
set.delete(targetChar);
}
}
return true;
};

for (let i = 0; i < s.length; i++) {
for (let j = i + 1; j <= s.length; j++) {
const str = s.slice(i, j);
if (str.length > max.length && isNice(str)) {
max = str;
}
}
}
return max;
};