-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-647-Palindromic-Substrings.java
42 lines (36 loc) · 1.33 KB
/
LeetCode-647-Palindromic-Substrings.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
// 1. DP (2-dimension)
/*
Runtime: 7 ms, faster than 30.40% of Java online submissions for Palindromic Substrings.
Memory Usage: 35.8 MB, less than 63.29% of Java online submissions for Palindromic Substrings.
*/
// public int countSubstrings(String s) {
// int len = s.length();
// boolean[][] dp = new boolean[len][len];
// int res = 0;
// for (int j = 0; j < len; j++) {
// for (int i = j; i >= 0; i--) {
// dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
// if (dp[i][j]) res++;
// }
// }
// return res;
// }
// 2. DP (1-d Array)
/*
Runtime: 4 ms, faster than 47.16% of Java online submissions for Palindromic Substrings.
Memory Usage: 34 MB, less than 100.00% of Java online submissions for Palindromic Substrings.
*/
public int countSubstrings(String s) {
int len = s.length();
boolean[] dp = new boolean[len];
int res = 0;
for (int i = len - 1; i >= 0; i--) {
for (int j = len - 1; j >= i; j--) {
dp[j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[j - 1]);
if (dp[j]) res++;
}
}
return res;
}
}