-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromicSubstrings.java
More file actions
41 lines (33 loc) · 1.04 KB
/
PalindromicSubstrings.java
File metadata and controls
41 lines (33 loc) · 1.04 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
/*
Given a string s, return the number of palindromic substrings in it.
A string is a palindrome when it reads the same backward as forward.
A substring is a contiguous sequence of characters within the string.
Example 1:
Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
*/
class Solution {
public int countSubstrings(String s) {
if(s.length() == 1) return 1;
int count_subs = 0;
for(int i = 0;i < s.length(); i++){
//counting odd length substrings
count_subs += substr(s, i, i);
//counting even length substrings
count_subs += substr(s, i, i+1);
}
return count_subs;
}
private int substr(String s, int left, int right){
int count = 0;
while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
left--;right++;count++;
}
return count;
}
}