-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPalindromicSubstrings.java
More file actions
60 lines (48 loc) · 1.73 KB
/
PalindromicSubstrings.java
File metadata and controls
60 lines (48 loc) · 1.73 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package string;
/**
* Description: https://leetcode.com/problems/palindromic-substrings
* Difficulty: Medium
*/
public class PalindromicSubstrings {
/**
* Time complexity: O(n^2)
* Space complexity: O(1)
*/
public int countSubstringsViaPalindromeExtending(String s) {
int count = 0;
for (int center = 0; center < s.length(); center++) {
count += extendAndCount(s, center, center); // count odd length palindromes: "[a]", "a[c]a", "ac[a]ca", etc.
count += extendAndCount(s, center - 1, center); // count even length palindromes: "[aa]", "a[bb]a", etc.
}
return count;
}
private int extendAndCount(String s, int left, int right) {
int count = 0;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
count++;
left--;
right++;
}
return count;
}
/**
* Time complexity: O(n^2)
* Space complexity: O(n^2)
*/
public int countSubstringsViaDP(String s) {
boolean[][] dp = new boolean[s.length()][s.length()];
int count = 0;
for (int left = s.length() - 1; left >= 0; left--) {
for (int right = left; right < s.length(); right++) {
if (s.charAt(left) != s.charAt(right)) continue;
int length = right - left + 1;
// "a", "aa" and "axa" are always palindromes
// for longer strings we check if the substring "inside" is palindrome
boolean isPalindrome = length <= 3 || dp[left + 1][right - 1];
dp[left][right] = isPalindrome;
count += isPalindrome ? 1 : 0;
}
}
return count;
}
}