64
64
65
65
<!-- 这里可写通用的实现逻辑 -->
66
66
67
+ ** 方法一:枚举两端字符 + 哈希表**
68
+
69
+ 由于字符串中只包含小写字母,因此我们可以直接枚举所有的两端字符。对于每一对两端字符 $c$,我们找出它们在字符串中第一次和最后一次出现的位置 $l$ 和 $r$,如果 $r - l > 1$,说明找到了满足条件的回文序列,我们将 $[ l+1,..r-1] $ 之间的字符去重后统计个数,即为以 $c$ 为两端字符的回文序列个数,加入答案中。
70
+
71
+ 枚举结束后,即可得到答案。
72
+
73
+ 时间复杂度 $O(n \times C)$,空间复杂度 $O(C)$,其中 $n$ 为字符串长度,而 $C$ 为字符集大小。本题中 $C = 26$。
74
+
67
75
<!-- tabs:start -->
68
76
69
77
### ** Python3**
73
81
``` python
74
82
class Solution :
75
83
def countPalindromicSubsequence (self , s : str ) -> int :
76
- res = 0
77
- for i in range (26 ):
78
- c = chr (ord (' a' ) + i)
79
- if c in s:
80
- l, r = s.index(c), s.rindex(c)
81
- chars = {s[j] for j in range (l + 1 , r)}
82
- res += len (chars)
83
- return res
84
+ ans = 0
85
+ for c in ascii_lowercase:
86
+ l, r = s.find(c), s.rfind(c)
87
+ if r - l > 1 :
88
+ ans += len (set (s[l + 1 : r]))
89
+ return ans
84
90
```
85
91
86
92
### ** Java**
@@ -90,16 +96,16 @@ class Solution:
90
96
``` java
91
97
class Solution {
92
98
public int countPalindromicSubsequence (String s ) {
93
- int res = 0 ;
99
+ int ans = 0 ;
94
100
for (char c = ' a' ; c <= ' z' ; ++ c) {
95
101
int l = s. indexOf(c), r = s. lastIndexOf(c);
96
- Set<Character > chars = new HashSet<> ();
102
+ Set<Character > cs = new HashSet<> ();
97
103
for (int i = l + 1 ; i < r; ++ i) {
98
- chars . add(s. charAt(i));
104
+ cs . add(s. charAt(i));
99
105
}
100
- res += chars . size();
106
+ ans += cs . size();
101
107
}
102
- return res ;
108
+ return ans ;
103
109
}
104
110
}
105
111
```
@@ -110,34 +116,31 @@ class Solution {
110
116
class Solution {
111
117
public:
112
118
int countPalindromicSubsequence(string s) {
113
- int res = 0;
119
+ int ans = 0;
114
120
for (char c = 'a'; c <= 'z'; ++c) {
115
121
int l = s.find_first_of(c), r = s.find_last_of(c);
116
- unordered_set<char > chars;
117
- for (int i = l + 1; i < r; ++i) {
118
- chars.insert(s[ i] );
119
- }
120
- res += chars.size();
122
+ unordered_set<char > cs;
123
+ for (int i = l + 1; i < r; ++i) cs.insert(s[ i] );
124
+ ans += cs.size();
121
125
}
122
- return res ;
126
+ return ans ;
123
127
}
124
128
};
125
129
```
126
130
127
131
### **Go**
128
132
129
133
```go
130
- func countPalindromicSubsequence(s string) int {
131
- res := 0
134
+ func countPalindromicSubsequence(s string) (ans int) {
132
135
for c := 'a'; c <= 'z'; c++ {
133
136
l, r := strings.Index(s, string(c)), strings.LastIndex(s, string(c))
134
- chars := make( map[byte]bool)
137
+ cs := map[byte]struct{}{}
135
138
for i := l + 1; i < r; i++ {
136
- chars [s[i]] = true
139
+ cs [s[i]] = struct{}{}
137
140
}
138
- res += len(chars )
141
+ ans += len(cs )
139
142
}
140
- return res
143
+ return
141
144
}
142
145
```
143
146
0 commit comments