8000 647. Palindromic Substrings · nullskill/leetcode@a58f140 · GitHub
[go: up one dir, main page]

Skip to content

Commit a58f140

Browse files
committed
647. Palindromic Substrings
1 parent 473916a commit a58f140

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/// The time complexity of the `countSubstrings` function is `O(n^2)`,
2+
/// where `n` is the length of the input string `s`. This is because we
3+
/// loop over each character in `s` and call the `countPalindromes`
4+
/// function twice for each character.
5+
/// The space complexity of the countSubstrings function is `O(1)`
6+
7+
class Solution {
8+
int countSubstrings(String s) {
9+
int count = 0;
10+
for (int i = 0; i < s.length; i++) {
11+
count += countPalindromes(s, i, i); // odd-length palindromes
12+
count += countPalindromes(s, i, i + 1); // even-length palindromes
13+
}
14+
return count;
15+
}
16+
17+
int countPalindromes(String s, int left, int right) {
18+
int count = 0;
19+
while (left >= 0 && right < s.length && s[left] == s[right]) {
20+
count++;
21+
left--;
22+
right++;
23+
}
24+
return count;
25+
}
26+
}
27+
28+
void main(List<String> args) {
29+
print(Solution().countSubstrings('aaa'));
30+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
647. Palindromic Substrings
2+
https://leetcode.com/problems/palindromic-substrings/
3+
4+
Given a string s, return the number of palindromic substrings in it.
5+
A string is a palindrome when it reads the same backward as forward.
6+
A substring is a contiguous sequence of characters within the string.
7+
8+
9+
Example 1:
10+
11+
Input: s = "abc"
12+
Output: 3
13+
Explanation: Three palindromic strings: "a", "b", "c".
14+
15+
Example 2:
16+
17+
Input: s = "aaa"
18+
Output: 6
19+
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
20+
21+
22+
Constraints:
23+
24+
1 <= s.length <= 1000
25+
s consists of lowercase English letters.

0 commit comments

Comments
 (0)
0