Longest Nice String
unknown
java
2 years ago
1.7 kB
12
Indexable
class Solution { public String longestNiceSubstring(String s) { String res = ""; int lenOfWholeString = s.length(); for (int start = 0; start < lenOfWholeString - 1; start++) { // if the remaning chars less than the res len found till now , no need to continue the iteration int remaningChars = lenOfWholeString - start; if (remaningChars <= res.length()) { break; } // here we are sure that the remaning chars count > the length of last res we found HashSet<Character> lowerSet = new HashSet<>(); HashSet<Character> upperConvertedToLowerSet = new HashSet<>(); // iterate over all chars starting from "start" // - if its lower , put it into the lowerSet // - if it is upper , convert it into lower and add it into the upperConvertedToLowerSet // - check if lowerSet equals upperConvertedToLowerSet , if so , update the solution for (int curr = start; curr < lenOfWholeString; curr++) { if(Character.isLowerCase(s.charAt(curr))) { lowerSet.add(s.charAt(curr)); } else { upperConvertedToLowerSet.add(Character.toLowerCase(s.charAt(curr))); } if (lowerSet.equals(upperConvertedToLowerSet)) { int currSolutionLen = curr - start + 1; if (currSolutionLen > res.length()) { res = s.substring(start, curr + 1); } } } } return res; } /* - i **/ }
Editor is loading...