-
Notifications
You must be signed in to change notification settings - Fork 1
/
PalindromicSubstrings.java
38 lines (37 loc) · 1.02 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
/**
* 647. Palindromic Substrings
* 中心扩散
* @author LBW
*/
public class PalindromicSubstrings {
public int countSubstrings(String s) {
int n = s.length(), i = 0;
int res = 0;
int left, right;
while (i < n) {
// i as center
res += 1;
left = i - 1;
right = i + 1;
while (left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
res += 1;
left -= 1;
right += 1;
}
// [i, i+1] as center
left = i;
right = i + 1;
while (left >= 0 && right < n && s.charAt(left) == s.charAt(right)) {
res += 1;
left -= 1;
right += 1;
}
i += 1;
}
return res;
}
public static void main(String[] args) {
PalindromicSubstrings palindromicSubstrings = new PalindromicSubstrings();
palindromicSubstrings.countSubstrings("fdsklf");
}
}