forked from HemangTheHuman/hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromic_substrings.cpp
More file actions
44 lines (38 loc) · 925 Bytes
/
Palindromic_substrings.cpp
File metadata and controls
44 lines (38 loc) · 925 Bytes
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
// 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: abc
// Output: 3
// Explanation: palindromic substrings are 'a', 'b' ,'c'
// Example 2:
// Input: aaa
// Output: 6
// Explanation: palindromic substrings are 'a', 'a' ,'aa','aa','a','aaa'
#include<bits/stdc++.h>
using namespace std;
bool checkPal(int i, int j, string str) {
while (i < j) {
if (str[i] != str[j]) return false;
i++;
j--;
}
return true;
}
int countSubstrings(string s) {
int n = s.length();
int sum = 0;
for (int i = 0; i < n; i++) {
for (int p = i; p < n; p++) {
if (checkPal(i, p, s) == true) {
sum++;
}
}
}
return sum;
}
int main() {
string s = "aaa";
cout << countSubstrings(s);
return 0;
}