Skip to content

Commit 5a0fe2a

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 647_Palindromic_Substrings.java
1 parent d63cd6c commit 5a0fe2a

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

Dynamic Programming/647_Palindromic_Substrings.java

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,25 @@ public int countSubstrings(String s) {
44
return 0;
55
}
66

7-
int result = 0, n = s.length();
8-
boolean[][] dp = new boolean[n][n];
7+
int result = 0;
98

10-
for (int i = n - 1; i >= 0; i--) {
11-
for (int j = i; j < n; j++) {
12-
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || dp[i + 1][j - 1]);
13-
14-
if (dp[i][j]) {
15-
++result;
16-
}
17-
}
9+
for (int i = 0; i < s.length(); i++) {
10+
result += expand(s, i, i);
11+
result += expand(s, i, i + 1);
1812
}
1913

2014
return result;
2115
}
16+
17+
private int expand(String str, int s, int e) {
18+
int count = 0;
19+
20+
while (s >= 0 && e < str.length() && str.charAt(s) == str.charAt(e)) {
21+
--s;
22+
++e;
23+
++count;
24+
}
25+
26+
return count;
27+
}
2228
}

0 commit comments

Comments
 (0)