You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/README_EN.md
+78-56
Original file line number
Diff line number
Diff line change
@@ -79,7 +79,13 @@ tags:
79
79
80
80
<!-- solution:start -->
81
81
82
-
### Solution 1
82
+
### Solution 1: Enumerate Both End Characters + Hash Table
83
+
84
+
Since the string contains only lowercase letters, we can directly enumerate all pairs of end characters. For each pair of end characters $c$, we find their first and last occurrence positions $l$ and $r$ in the string. If $r - l > 1$, it means we have found a palindromic subsequence that meets the conditions. We then count the number of unique characters between $[l+1,..r-1]$, which gives the number of palindromic subsequences with $c$ as the end characters, and add it to the answer.
85
+
86
+
After enumerating all pairs, we get the answer.
87
+
88
+
The time complexity is $O(n \times |\Sigma|)$, where $n$ is the length of the string and $\Sigma$ is the size of the character set. In this problem, $|\Sigma| = 26$. The space complexity is $O(|\Sigma|)$ or $O(1)$.
83
89
84
90
<!-- tabs:start -->
85
91
@@ -104,11 +110,14 @@ class Solution {
104
110
int ans =0;
105
111
for (char c ='a'; c <='z'; ++c) {
106
112
int l = s.indexOf(c), r = s.lastIndexOf(c);
107
-
Set<Character> cs=newHashSet<>();
113
+
int mask=0;
108
114
for (int i = l +1; i < r; ++i) {
109
-
cs.add(s.charAt(i));
115
+
int j = s.charAt(i) -'a';
116
+
if ((mask >> j &1) ==0) {
117
+
mask |=1<< j;
118
+
++ans;
119
+
}
110
120
}
111
-
ans += cs.size();
112
121
}
113
122
return ans;
114
123
}
@@ -124,9 +133,14 @@ public:
124
133
int ans = 0;
125
134
for (char c = 'a'; c <= 'z'; ++c) {
126
135
int l = s.find_first_of(c), r = s.find_last_of(c);
0 commit comments