Longest Nice Substring LeetCode solution in Java

1
class Solution {
2
public String longestNiceSubstring(String s) {
3
String result = "";
4
// take first index, go from 0 to length-1 of the string
5
for (int i = 0; i < s.length(); i++) {
6
// take second index, this should go up to the length of the string <=
7
for (int j = i + 1; j <= s.length(); j++) {
8
// get the substring for the index range from i to j
9
String temp = s.substring(i, j);
10
// if length of the substring should be greater than 1
11
// if the length should be greater that the previous computed result
12
// if the substring is valid Nice String
13
// then update the result with the current substring from range i and j
14
if (temp.length() > 1 && result.length() < temp.length() && checkNice(temp)) result = temp;
15
}
16
}
17
return result;
18
}
19

20
// validate Nice String check
21
public boolean checkNice(String temp) {
22
// add substring to the set
23
Set<Character> s = new HashSet<>();
24
for (char ch : temp.toCharArray()) s.add(ch);
25

26
// return false If you do not find both lower case and upper case in the sub string
27
// for e.g 'aAa' substring added to set will have both a and A in the substring which is valid
28
// 'azaA' substring will fail for 'z'
29
// 'aaaaaaaa' will return "" as result
30
// make sure that the substring contains both lower and upper case
31
for (char ch : s)
32
if (s.contains(Character.toUpperCase(ch)) != s.contains(Character.toLowerCase(ch)))
33
return false;
34
return true;
35
}
36
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0