当前位置:网站首页>Count the number of different palindrome subsequences in the string
Count the number of different palindrome subsequences in the string
2022-06-29 00:52:00 【GreyZeng】
Count the number of different palindrome subsequences in the string
author :Grey
Original address : Count the number of different palindrome subsequences in the string
Problem description
Given a string str, Of course, many subsequences can be generated , Returns how many subsequences are palindromes , Empty sequences are not palindromes , such as ,str = “aba” Palindrome subsequence has
{a}:0 In position a
{a}:2 In position a
{a,a}
{b}
{a,b,a}
So back 5.
Violence solution
Enumerate each subsequence , Then determine whether the subsequence is a palindrome , The code is as follows
public static int ways1(String str) {
if (str == null || str.length() == 0) {
return 0;
}
char[] s = str.toCharArray();
char[] path = new char[s.length];
return process(str.toCharArray(), 0, path, 0);
}
// Enumerate each location to or from , Get the number of palindrome subsequences
public static int process(char[] s, int si, char[] path, int pi) {
if (si == s.length) {
return isP(path, pi) ? 1 : 0;
}
int ans = process(s, si + 1, path, pi);
path[pi] = s[si];
ans += process(s, si + 1, path, pi + 1);
return ans;
}
// Judge path In a string 0...pi-1 Is it a palindrome
public static boolean isP(char[] path, int pi) {
if (pi == 0) {
return false;
}
int L = 0;
int R = pi - 1;
while (L < R) {
if (path[L++] != path[R--]) {
return false;
}
}
return true;
}
Dynamic programming solution
Define a two-dimensional array dp, The array length is assumed to be n
int[][] dp = new int[n][n]
dp[i][j] The meaning is : character string [i...j] The maximum number of palindrome subsequences that can be obtained in the interval , therefore ,dp[0][n-1] The value of is the final answer we need to find .
according to dp The meaning of array , We can get , Two dimensional matrix dp The values on the diagonals in are all 1, The position above the diagonal can also be easily obtained , See note below
// The values on the diagonal are all 1
for (int i = 0; i < n; i++) {
dp[i][i] = 1;
}
// The position above the diagonal , namely dp[i][i+1] Value on
// If str[i] == str[i+1], such as :aa, There are three palindrome subsequences , Namely {a},{a},{aa}
// If str[i] != str[i+1], such as :ab, There are two palindrome subsequences , Namely {a},{b}
for (int i = 0; i < n - 1; i++) {
dp[i][i+1] = str[i] == str[i+1] ? 3 : 2;
}
Next, consider the general location dp[i][j], There can be several situations as follows :
Situation 1 ,i The character of position is discarded , that dp[i][j] = dp[i+1][j];
Situation two ,j The character of position is discarded , that dp[i][j] = dp[i][j-1];
Based on case one and case two ,
dp[i][j] = dp[i+1][j] + dp[i][j-1]
This is the time , In fact, it is a heavy part , The heavy part is dp[i+1][j-1], therefore
dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]
If str[i] == str[j], Then there is case three , Case III medium ,str[i] and str[j] But keep it all , And interval [i+1...j-1] Form palindrome string ,str[i] It can also be used alone with str[j] Form a palindrome string . therefore , Situation three
// dp[i][j] In two parts
// among :
// The first part :dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] Express i Location and j When the position is abandoned , The number of answers obtained
// The second part :dp[i + 1][j - 1] + 1 In case 3 , Use at the same time str[i] and str[j] The number of answers from the position
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] + dp[i + 1][j - 1] + 1
Dynamic programming solution of the complete code
public static int ways2(String s) {
if (s == null || s.length() == 0) {
return 0;
}
char[] str = s.toCharArray();
int n = str.length;
int[][] dp = new int[n][n];
// The diagonals are 1
for (int i = 0; i < n; i++) {
dp[i][i] = 1;
}
for (int i = 0; i < n - 1; i++) {
dp[i][i + 1] = str[i] == str[i + 1] ? 3 : 2;
}
for (int i = n - 3; i >= 0; i--) {
for (int j = i + 2; j < n; j++) {
// subtract dp[i+1][j-1] It's because it's repeated
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1];
if (str[i] == str[j]) {
// dp[i][j] In two parts
// among :
// The first part :dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] Express i Location and j When the position is abandoned , The number of answers obtained
// The second part :dp[i + 1][j - 1] + 1 In case 3 , Use at the same time str[i] and str[j] The number of answers from the position
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] + dp[i + 1][j - 1] + 1;
}
}
}
return dp[0][n - 1];
}
Similar problems
LeetCode 730. Statistics of different palindrome subsequences
more
边栏推荐
- Reasons for high price of optical fiber slip ring
- Browser cache library design summary (localstorage/indexeddb)
- Notes on the infrastructure of large websites
- Leetcode daily question: implementing strstr()
- Cross domain problem of canvas drawing caused by background image cache
- Précautions d'installation et d'utilisation des joints rotatifs
- Daily practice: delete duplicates in the ordered array
- 统计字符串中不同回文子序列的个数
- Redis常用命令手册
- Redis common command manual
猜你喜欢

FSS object storage how to access the Intranet
![[image registration] SAR image registration based on particle swarm optimization Improved SIFT with matlab code](/img/b5/02979b50db885f0606dce455182ac4.jpg)
[image registration] SAR image registration based on particle swarm optimization Improved SIFT with matlab code

How to mount FSS object storage locally

Use and principle of handlerthread
UI高度自适应的修改方案

Seven mistakes in IT Governance and how to avoid them

EasyCVR服务private.pem文件被清空,导致无法正常启动该如何处理?
![[image detection] recognition of the front and back of a coin based on texture features with matlab code attached](/img/84/0a364adcd373cc40c9bc7b70d50f93.jpg)
[image detection] recognition of the front and back of a coin based on texture features with matlab code attached

Document management.

Structure of the actual combat battalion | module 5
随机推荐
Daily question 1: the number of numbers in the array
[image registration] SAR image registration based on particle swarm optimization Improved SIFT with matlab code
Mask wearing face data set and mask wearing face generation method
[200 opencv routines] 101 adaptive median filter
Daily question 1: missing numbers
Go1.18 new feature: discard strings Title Method, a new pit!
Xuetong denies that the theft of QQ number is related to it: it has been reported; IPhone 14 is ready for mass production: four models are launched simultaneously; Simple and elegant software has long
Is the fund reliable and safe
Précautions d'installation et d'utilisation des joints rotatifs
【SV 基础】queue 的一些用法
浏览器缓存库设计总结(localStorage/indexedDB)
Nodejs安装和下载
[gym 102423]-elven efficiency | thinking
Drawing ECG curve with WPF
分析框架——用户体验度量数据体系搭建
【leetcode】153. Find the lowest value in the rotation sort array
[MCU club] design of GSM version of range hood based on MCU [simulation design]
盘点 6 月 yyds 的开源项目!
Résumé de Manon, 25 ans, diplômé en trois ans
Report on the convenient bee Lantern Festival: the first peak sales of pasta products this year; prefabricated wine dumplings became the winners