统计不同回文子序列
难度:
标签:
题目描述
代码结果
运行时间: 296 ms, 内存: 16.2 MB
/*
* Approach:
* Using Java Streams, we can calculate the number of distinct palindromic subsequences by first identifying
* all subsequences of the string and then filtering out the palindromic ones. We use a set to keep track of
* distinct palindromic subsequences and return the size of the set.
*/
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SolutionStream {
private static final int MOD = 1_000_000_007;
public int countPalindromicSubsequences(String s) {
Set<String> palindromicSubsequences = IntStream.range(0, s.length())
.boxed()
.flatMap(i -> IntStream.range(i + 1, s.length() + 1)
.mapToObj(j -> s.substring(i, j)))
.filter(this::isPalindrome)
.collect(Collectors.toSet());
return palindromicSubsequences.size() % MOD;
}
private boolean isPalindrome(String str) {
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left++) != str.charAt(right--)) {
return false;
}
}
return true;
}
}
解释
方法:
这个题解使用动态规划的思想解决问题。通过维护两个数组nxt和use,nxt[i]表示以s[i]结尾的回文子序列个数,use[i]表示以s[i]结尾且s[i]已经使用过的回文子序列个数。遍历字符串s,对于每个位置j,从j-1到0遍历所有i,如果s[i]==s[j],则将nxt[i]加到答案中,并更新nxt[i]和use[i]。如果s[i]!=s[j],则只更新nxt[i]。最终返回答案对10^9+7取模的结果。
时间复杂度:
O(n^2)
空间复杂度:
O(n)
代码细节讲解
🦆
在动态规划的解决方案中,数组`nxt`和`use`的具体作用是什么?能否详细解释它们如何跟踪子序列的状态?
▷🦆
为什么在内层循环中,当`s[i] == s[j]`时,需要进行`nxt[i]`和`use[i]`的更新,这种更新方式具体是如何帮助统计回文子序列的?
▷🦆
在算法中,变量`x`的角色和意义是什么?它在循环中是如何被更新和使用的?
▷