LeetCode 1763: Longest Nice Substring Solution

Master LeetCode problem 1763 (Longest Nice Substring), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To find the longest nice substring in a given string, we can iterate through all possible substrings of the input string and check if each substring is nice. We can do this by iterating over each character of the substring and keeping track of the uppercase and lowercase characters that appear in that substring. If for every letter that appears in the substring, both uppercase and lowercase versions are present, then it is a nice substring.

We start with the longest possible substring and gradually decrease its length until we find a nice substring. We can use a nested loop to generate all possible substrings efficiently. The time complexity of this approach is O(n^3) where n is the length of the input string.

Solution Code

class Solution {
    public String longestNiceSubstring(String s) {
        String res = "";
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + 1; j < s.length(); j++) {
                String sub = s.substring(i, j + 1);
                if (isNice(sub) && sub.length() > res.length()) {
                    res = sub;
                }
            }
        }
        return res;
    }
    
    private boolean isNice(String s) {
        boolean[] upper = new boolean[26];
        boolean[] lower = new boolean[26];
        for (char c : s.toCharArray()) {
            if (Character.isUpperCase(c)) {
                upper[c - 'A'] = true;
            } else {
                lower[c - 'a'] = true;
            }
        }
        for (int i = 0; i < 26; i++) {
            if (upper[i] != lower[i]) {
                return false;
            }
        }
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1763 (Longest Nice Substring)?

This page provides optimized solutions for LeetCode problem 1763 (Longest Nice Substring) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1763 (Longest Nice Substring)?

The time complexity for LeetCode 1763 (Longest Nice Substring) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1763 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1763 in Java, C++, or Python.

Back to LeetCode Solutions