Formatted question description: https://leetcode.ca/all/1763.html

1763. Longest Nice Substring

Level

Easy

Description

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.

Example 4:

Input: s = “dDzeE”

Output: “dD”

Explanation: Both “dD” and “eE” are the longest nice substrings. As there are multiple longest nice substrings, return “dD” since it occurs earlier.

Constraints:

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

Solution

Loop over all possible substrings of s. For each substring, check whether it is nice by using a hash set. Among all nice substrings, find the one that is the longest and has the earliest occurrence.

class Solution {
    public String longestNiceSubstring(String s) {
        int maxLength = 0;
        String longest = "";
        int length = s.length();
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j <= length; j++) {
                String substr = s.substring(i, j);
                if (isNice(substr)) {
                    if (substr.length() > maxLength) {
                        maxLength = substr.length();
                        longest = substr;
                    }
                }
            }
        }
        return longest;
    }

    public boolean isNice(String s) {
        Set<Character> set = new HashSet<Character>();
        int length = s.length();
        for (int i = 0; i < length; i++)
            set.add(s.charAt(i));
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            char difCase = c <= 'Z' ? (char) (c + 'a' - 'A') : (char) (c - 'a' + 'A');
            if (!set.contains(difCase))
                return false;
        }
        return true;
    }
}

All Problems

All Solutions