-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathPalindromicSubstrings.java
87 lines (58 loc) · 1.58 KB
/
PalindromicSubstrings.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
Source: https://leetcode.com/problems/palindromic-substrings/
1st Approach (Brute force)
Basic Idea:
Create all possible subarrays and check if each subarray is palindrome or not
Time: O(n ^ 3), where n is the length of the given String(s)
Space: O(1), in-place
*/
class Solution {
public int countSubstrings(String s) {
int len = s.length();
int count = 0;
for(int i = 0; i < len; ++i) {
for(int j = i; j < len; ++j) {
if(isPalindrome(s.substring(i, j + 1))) {
++count;
}
}
}
return count;
}
private boolean isPalindrome(String sub) {
int start = 0;
int end = sub.length() - 1;
while(start < end && sub.charAt(start) == sub.charAt(end)) {
++start;
--end;
}
return start >= end;
}
}
/*
Approach 2
Basic Idea:
Start from each index and treat each index as mid point and extend palindrome from that index for both odd and even lengths
Time: O(n ^ 2), where n is the length of the given String(s)
Space: O(n), char array is needed access characters of String(s) and to avoid charAt() repeatidly
*/
class Solution {
private int count;
private int len;
public int countSubstrings(String s) {
char[] sChars = s.toCharArray();
len = sChars.length;
for(int i = 0; i < len; ++i) {
extendPalindrome(sChars, i, i);
extendPalindrome(sChars, i, i + 1);
}
return count;
}
private void extendPalindrome(char[] sChars, int start, int end) {
while(start >= 0 && end < len && sChars[start] == sChars[end]) {
++count;
--start;
++end;
}
}
}