Skip to content

Commit ca71a8a

Browse files
solves longest nice substring
1 parent 1bc45e7 commit ca71a8a

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@
430430
| 1748 | [Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements) | [![Java](assets/java.png)](src/SumOfUniqueElements.java) | |
431431
| 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated) | [![Java](assets/java.png)](src/CheckIfArrayIsSortedAndRotated.java) | |
432432
| 1758 | [Minimum Changes To Make Alternating Binary String](https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string) | [![Java](assets/java.png)](src/MinimumChangesToMakeAlternatingBinaryString.java) | |
433-
| 1763 | [Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring) | | |
433+
| 1763 | [Longest Nice Substring](https://leetcode.com/problems/longest-nice-substring) | [![Java](assets/java.png)](src/LongestNiceSubstring.java) | |
434434
| 1768 | [Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately) | | |
435435
| 1773 | [Count Items Matching a Rule](https://leetcode.com/problems/count-items-matching-a-rule) | | |
436436
| 1779 | [Find Nearest Point That Has the Same X or Y Coordinate](https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate) | | |

src/LongestNiceSubstring.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
public class LongestNiceSubstring {
5+
public String longestNiceSubstring(String s) {
6+
String longestNiceSubString = "";
7+
Set<Character> alphabets = new HashSet<>();
8+
for (int i = 0 ; i < s.length() ; i++) {
9+
for (int j = i ; j < s.length() ; j++) {
10+
alphabets.add(s.charAt(j));
11+
if (containsBotLowerAndUpperCase(alphabets) && j - i + 1 > longestNiceSubString.length()) {
12+
longestNiceSubString = s.substring(i, j + 1);
13+
}
14+
}
15+
alphabets.clear();
16+
}
17+
return longestNiceSubString;
18+
}
19+
20+
private boolean containsBotLowerAndUpperCase(Set<Character> alphabets) {
21+
for (char alphabet : alphabets) {
22+
if (!alphabets.contains(inverse(alphabet))) {
23+
return false;
24+
}
25+
}
26+
return true;
27+
}
28+
29+
private char inverse(char c) {
30+
return Character.isLowerCase(c) ? Character.toUpperCase(c) : Character.toLowerCase(c);
31+
}
32+
33+
private Set<Character> getCharacters(String s, int start, int end) {
34+
final Set<Character> set = new HashSet<>();
35+
for (int index = start ; index <= end ; index++) {
36+
set.add(s.charAt(index));
37+
}
38+
return set;
39+
}
40+
}

0 commit comments

Comments
 (0)