-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1930. Unique Length-3 Palindromic Subsequences.java
More file actions
78 lines (60 loc) · 2.07 KB
/
1930. Unique Length-3 Palindromic Subsequences.java
File metadata and controls
78 lines (60 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
1930. Unique Length-3 Palindromic Subsequences
Solved
Medium
Topics
premium lock icon
Companies
Hint
Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
Example 1:
Input: s = "aabca"
Output: 3
Explanation: The 3 palindromic subsequences of length 3 are:
- "aba" (subsequence of "aabca")
- "aaa" (subsequence of "aabca")
- "aca" (subsequence of "aabca")
Example 2:
Input: s = "adc"
Output: 0
Explanation: There are no palindromic subsequences of length 3 in "adc".
Example 3:
Input: s = "bbcbaba"
Output: 4
Explanation: The 4 palindromic subsequences of length 3 are:
- "bbb" (subsequence of "bbcbaba")
- "bcb" (subsequence of "bbcbaba")
- "bab" (subsequence of "bbcbaba")
- "aba" (subsequence of "bbcbaba")
Constraints:
3 <= s.length <= 105
s consists of only lowercase English letters.class Solution {
public int countPalindromicSubsequence(String s) {
Set<Character> letters = new HashSet();
for (Character c: s.toCharArray()) {
letters.add(c);
}
int ans = 0;
for (Character letter : letters) {
int i = -1;
int j = 0;
for (int k = 0; k < s.length(); k++) {
if (s.charAt(k) == letter) {
if (i == -1) {
i = k;
}
j = k;
}
}
Set<Character> between = new HashSet();
for (int k = i + 1; k < j; k++) {
between.add(s.charAt(k));
}
ans += between.size();
}
return ans;
}
}