forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Java solution to 1930 Unique 3 Length Palindromic Subsequences
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
class Solution { | ||
public int countPalindromicSubsequence(String s) { | ||
char[] letters = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', | ||
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', | ||
'w', 'x', 'y', 'z'}; | ||
Set<Character> left = new HashSet<>(); | ||
Map<Character, Integer> right = new HashMap<>(); | ||
for(char c : s.toCharArray()) { | ||
right.put(c, right.getOrDefault(c, 0) + 1); | ||
} | ||
Set<String> res = new HashSet<>(); | ||
|
||
for(int mid = 0; mid < s.length(); mid++) { | ||
char c = s.charAt(mid); | ||
|
||
right.put(c, right.get(c)-1); | ||
if(right.get(c) == 0) { | ||
right.remove(c); | ||
} | ||
|
||
for(int i=0; i<26; i++) { | ||
if(left.contains(letters[i]) && right.containsKey(letters[i])) { | ||
res.add("" + letters[i] + c + letters[i]); | ||
} | ||
} | ||
|
||
left.add(c); | ||
} | ||
|
||
return res.size(); | ||
} | ||
} |