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.
Approach
Java
import java.util.HashSet;public class LongestNiceSubstring {public static void main(String[] args) {String s = "YazaAay";System.out.println(longestNiceSubstring(s));}static String longestNiceSubstring(String s) {// if size of string is less than// 2 then return null string// base caseif (s.length() < 2)return "";HashSet<Character> st = new HashSet<>();// add all characters of string into// the unordered setfor (int i = 0; i < s.length(); i++)st.add(s.charAt(i));for (int i = 0; i < s.length(); i++) {if (!st.contains(Character.toUpperCase(s.charAt(i)))|| !st.contains(Character.toLowerCase(s.charAt(i)))) {// call for left halfString s1 = longestNiceSubstring(s.substring(0, i));// call for right halfString s2 = longestNiceSubstring(s.substring(i + 1));// return the string which is biggerif (s1.length() >= s2.length())return s1;return s2;}}return s;}}
C++
#include <bits/stdc++.h>using namespace std;string longestNiceSubstring(string s){//if size of string is less than//2 then return null string//base caseif (s.size() < 2)return "";unordered_set<char> st;//add all characters of string into//the unordered setfor (int i = 0; i < s.size(); i++)st.insert(s[i]);for (int i = 0; i < s.size(); i++){if (st.find(toupper(s[i])) == st.end() ||st.find(tolower(s[i])) == st.end()){//call for left halfstring s1 = longestNiceSubstring(s.substr(0, i));//call for right halfstring s2 = longestNiceSubstring(s.substr(i + 1));//return the string which is biggerif (s1.size() >= s2.size())return s1;return s2;}}return s;}int main(){string s = "YazaAay";cout << longestNiceSubstring(s) << "\n";return 0;}
No comments:
Post a Comment