Skip to content

Commit 359dcd0

Browse files
add 647
1 parent aa48b81 commit 359dcd0

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Your ideas/fixes/algorithms are more than welcome!
2121
| # | Title | Solutions | Time | Space | Difficulty | Tag | Notes
2222
|-----|----------------|---------------|---------------|---------------|-------------|--------------|-----
2323
|648|[Replace Words](https://leetcode.com/problems/replace-words/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_648.java) | O(n) |O(n) | Medium | Trie
24+
|647|[Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_647.java) | O(n^2) |O(1) | Medium | DP
2425
|646|[Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_646.java) | O(nlogn) |O(1) | Medium | DP
2526
|645|[Set Mismatch](https://leetcode.com/problems/set-mismatch/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_645.java) | O(nlogn) |O(1) | Easy |
2627
|644|[Maximum Average Subarray II](https://leetcode.com/problems/maximum-average-subarray-ii/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_644.java) | |O(1) | Hard | Binary Search
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.fishercoder.solutions;
2+
3+
/**
4+
* 647. Palindromic Substrings
5+
*
6+
* Given a string, your task is to count how many palindromic substrings in this string.
7+
* The substrings with different start indexes or end indexes are counted
8+
* as different substrings even they consist of same characters.
9+
10+
Example 1:
11+
Input: "abc"
12+
Output: 3
13+
Explanation: Three palindromic strings: "a", "b", "c".
14+
15+
Example 2:
16+
Input: "aaa"
17+
Output: 6
18+
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
19+
20+
Note:
21+
The input string length won't exceed 1000.
22+
23+
*/
24+
public class _647 {
25+
26+
/**reference: https://discuss.leetcode.com/topic/96819/java-solution-8-lines-extendpalindrome*/
27+
public int countSubstrings(String s) {
28+
int count = 0;
29+
for (int i = 0; i < s.length(); i++) {
30+
count += extendPalindrome(s, i, i);//odd length
31+
count += extendPalindrome(s, i, i+1);//even length
32+
}
33+
return count;
34+
}
35+
36+
private int extendPalindrome(String s, int left, int right) {
37+
int count = 0;
38+
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
39+
count++;
40+
left--;
41+
right++;
42+
}
43+
return count;
44+
}
45+
}

0 commit comments

Comments
 (0)