Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 30ab3a3

Browse files
Solved problems
1 parent afac3f6 commit 30ab3a3

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package dynamic_programming;
2+
3+
import java.util.Arrays;
4+
5+
/** Created by gouthamvidyapradhan on 10/04/2021 */
6+
public class CountDifferentPalindromicSubsequences {
7+
public static void main(String[] args) {
8+
System.out.println(
9+
new CountDifferentPalindromicSubsequences()
10+
.countPalindromicSubsequences(
11+
"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba"));
12+
}
13+
14+
private long[][][] DP;
15+
final char[] chars = {'a', 'b', 'c', 'd'};
16+
final int MOD = (int) 1e9 + 7;
17+
18+
public int countPalindromicSubsequences(String S) {
19+
DP = new long[S.length()][S.length()][4];
20+
for (int i = 0; i < S.length(); i++) {
21+
for (int j = 0; j < S.length(); j++) {
22+
Arrays.fill(DP[i][j], -1);
23+
}
24+
}
25+
long result = 0L;
26+
for (char c : chars) {
27+
long r = dp(0, S.length() - 1, S, c);
28+
result = ((result + r) % MOD);
29+
}
30+
return (int) result;
31+
}
32+
33+
private long dp(int i, int j, String s, char c) {
34+
if (i > j) return 0;
35+
else if (DP[i][j][c - 'a'] != -1) return DP[i][j][c - 'a'];
36+
else if (s.charAt(i) == s.charAt(j) && s.charAt(i) == c) {
37+
if (i == j) return 1;
38+
else {
39+
long sum = 0L;
40+
for (char aChar : chars) {
41+
long r = dp(i + 1, j - 1, s, aChar);
42+
if (aChar == c) {
43+
r = ((r + 2) % MOD);
44+
}
45+
sum = ((sum + r) % MOD);
46+
}
47+
DP[i][j][c - 'a'] = sum;
48+
return DP[i][j][c - 'a'];
49+
}
50+
} else if (s.charAt(i) == c) {
51+
DP[i][j][c - 'a'] = dp(i, j - 1, s, c);
52+
return DP[i][j][c - 'a'];
53+
} else if (s.charAt(j) == c) {
54+
DP[i][j][c - 'a'] = dp(i + 1, j, s, c);
55+
return DP[i][j][c - 'a'];
56+
} else {
57+
DP[i][j][c - 'a'] = dp(i + 1, j - 1, s, c);
58+
return DP[i][j][c - 'a'];
59+
}
60+
}
61+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /