• 欢迎光临~

# [LeetCode] 1763. Longest Nice Substring

A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, "abABB" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, "abA" is not because 'b' appears, but 'B' does not.

Given a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.

Example 1:

Input: s = "YazaAay"
Output: "aAa"
Explanation: "aAa" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.
"aAa" is the longest nice substring.

Example 2:

Input: s = "Bb"
Output: "Bb"
Explanation: "Bb" is a nice string because both 'B' and 'b' appear. The whole string is a substring.

Example 3:

Input: s = "c"
Output: ""
Explanation: There are no nice substrings.

Constraints:

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

Java实现

1 class Solution {
2     public String longestNiceSubstring(String s) {
3         // corner case
4         if (s.length() < 2) {
5             return "";
6         }
7
8         // normal case
9         char[] input = s.toCharArray();
10         HashSet<Character> set = new HashSet<>();
11         for (char c : input) {
13         }
14
15         for (int i = 0; i < input.length; i++) {
16             char c = input[i];
17             if (set.contains(Character.toUpperCase(c)) && set.contains(Character.toLowerCase(c))) {
18                 continue;
19             }
20             String sub1 = longestNiceSubstring(s.substring(0, i));
21             String sub2 = longestNiceSubstring(s.substring(i + 1));
22             return sub1.length() >= sub2.length() ? sub1 : sub2;
23         }
24         return s;
25     }
26 }

Java实现

1 class Solution {
2     public String longestNiceSubstring(String s) {
3         int len = s.length();
4         int maxPos = 0;
5         int maxLen = 0;
6         for (int i = 0; i < len; i++) {
7             int lower = 0;
8             int upper = 0;
9             for (int j = i; j < len; j++) {
10                 if (Character.isLowerCase(s.charAt(j))) {
11                     lower |= 1 << (s.charAt(j) - 'a');
12                 } else {
13                     upper |= 1 << (s.charAt(j) - 'A');
14                 }
15                 if (lower == upper && j - i + 1 > maxLen) {
16                     maxPos = i;
17                     maxLen = j - i + 1;
18                 }
19             }
20         }
21         return s.substring(maxPos, maxPos + maxLen);
22     }
23 }

LeetCode 题目总结