Skip to content

Commit 1bc3223

Browse files
committed
solve 647.palindromic-substrings
1 parent 273e642 commit 1bc3223

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* @lc app=leetcode id=647 lang=java
3+
*
4+
* [647] Palindromic Substrings
5+
*
6+
* https://leetcode.com/problems/palindromic-substrings/description/
7+
*
8+
* algorithms
9+
* Medium (57.70%)
10+
* Likes: 1608
11+
* Dislikes: 82
12+
* Total Accepted: 116.8K
13+
* Total Submissions: 202K
14+
* Testcase Example: '"abc"'
15+
*
16+
* Given a string, your task is to count how many palindromic substrings in
17+
* this string.
18+
*
19+
* The substrings with different start indexes or end indexes are counted as
20+
* different substrings even they consist of same characters.
21+
*
22+
* Example 1:
23+
*
24+
*
25+
* Input: "abc"
26+
* Output: 3
27+
* Explanation: Three palindromic strings: "a", "b", "c".
28+
*
29+
*
30+
*
31+
*
32+
* Example 2:
33+
*
34+
*
35+
* Input: "aaa"
36+
* Output: 6
37+
* Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
38+
*
39+
*
40+
*
41+
*
42+
* Note:
43+
*
44+
*
45+
* The input string length won't exceed 1000.
46+
*
47+
*
48+
*
49+
*
50+
*/
51+
class Solution {
52+
public int countSubstrings(String s) {
53+
int count = 0;
54+
for (int i = 0; i < s.length(); i++) {
55+
count += palindromic(s, i, i);
56+
count += palindromic(s, i, i + 1);
57+
}
58+
return count;
59+
}
60+
61+
public int palindromic(String s, int left, int right) {
62+
int count = 0;
63+
while (left >= 0 && right < s.length()
64+
&& (s.charAt(left) == s.charAt(right))) {
65+
left--;
66+
right++;
67+
count++;
68+
}
69+
return count;
70+
}
71+
}
72+

0 commit comments

Comments
 (0)