Leetcode 1763. Longest Nice Substring
A string s
is considered nice if, for every character in s
, the corresponding uppercase and lowercase characters both exist in s
.
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 no nice substrings, return an empty string.
s
will always have at least one character.s
itself is nice, return it.#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
// Helper function to check if a string is nice
bool isNice(const string &s) {
unordered_set<char> charset(s.begin(), s.end());
for (char c : charset) {
if ((isupper(c) && charset.count(tolower(c)) == 0) ||
(islower(c) && charset.count(toupper(c)) == 0)) {
return false;
}
}
return true;
}
// Recursive function to find the longest nice substring
string longestNiceSubstring(const string &s) {
int n = s.length();
if (n < 2) return "";
// If the entire string is nice, return it
if (isNice(s)) return s;
// Try to find the longest nice substring by splitting
for (int i = 0; i < n; ++i) {
string left = s.substr(0, i);
string right = s.substr(i + 1, n - i - 1);
if (!isNice(s.substr(i, 1))) {
string longestLeft = longestNiceSubstring(left);
string longestRight = longestNiceSubstring(right);
return longestLeft.length() >= longestRight.length() ? longestLeft : longestRight;
}
}
return "";
}
int main() {
string s;
cout << "Enter the string: ";
cin >> s;
string result = longestNiceSubstring(s);
cout << "Longest Nice Substring: " << result << endl;
return 0;
}
This ensures that the solution finds the longest nice substring by systematically breaking down the problem using a divide-and-conquer approach.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?