-
Notifications
You must be signed in to change notification settings - Fork 1
/
34_palindromic-substrings.cpp
55 lines (47 loc) · 1.26 KB
/
34_palindromic-substrings.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// DATE: 05-Aug-2023
/* PROGRAM: 34_String - Palindromic Substrings
https://leetcode.com/problems/palindromic-substrings/
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".
*/
// @ankitsamaddar @Aug_2023
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int countSubstrings(string s) {
int res = 0;
for (int i = 0; i < s.length(); i++) {
// odd length
res += countPalindrome(s, i, i);
// even length
res += countPalindrome(s, i, i + 1);
}
return res;
}
int countPalindrome(string s, int l, int r) {
int res = 0;
while (l >= 0 and r <= s.length() and (s[l] == s[r])) {
res++;
l--;
r++;
}
return res;
}
};
int main() {
string s = "aaa";
Solution sol;
cout << sol.countSubstrings(s) << endl;
return 0;
}