这一题题目不难理解,就是在字符串中寻找有多少个独一无二的回文,只不过这个回文可以不相邻,而且长度只有3。固定首尾,然后再确定中间的字符,加一个去重即可(Set)。
时间复杂度过大,n的3次方
这里的思路比较耿直,直接用3层循环来做
i来寻找首,j来寻找尾,k在中间进行累加即可
最后利用set来进行去重
只不过这里不能ac,时间复杂度过大。
js
var countPalindromicSubsequence = function (s) {
let set = new Set();
for (let i = 0; i < s.length; ++i) {
for (let j = s.length - 1; j > i + 1; --j) {
if (s[i] === s[j]) {
for (let k = i + 1; k < j; ++k) {
set.add(s[i] + s[k] + s[j]);
}
}
}
}
return set.size
};
ac
这个解法时间复杂度就是n,准确来说是26*n,存在常数,即O(n)
寻找每个字符首次出现的位置,还有最后一次出现的位置
如果这两个位置的字符索引不相等,那么就可以形成回文
js
var countPalindromicSubsequence = function (s) {
const firstIndex = new Array(26).fill(-1)
const lastIndex = new Array(26).fill(-1)
for(let i = 0; i < s.length; ++i){
const charCode = s.charCodeAt(i) - 'a'.charCodeAt(0)
if(firstIndex[charCode] === -1){
firstIndex[charCode] = i
}
lastIndex[charCode] = i
}
let sum = 0
for(let i = 0; i < 26; ++i){
let first = firstIndex[i]
let last = lastIndex[i]
if(first == last) continue
let charSet = new Set()
for(let j = first + 1; j < last; ++j){
charSet.add(s[j])
}
sum += charSet.size
}
return sum
};