count substrings codechef solution in c++
Sure! Here is a solution to count substrings in C++ for the CodeChef problem.
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t; // Read the number of test cases
while (t--) {
string s;
cin >> s; // Read the input string
int count = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// Check if the substring from index i to index j is a palindrome
bool isPalindrome = true;
for (int k = i; k <= (i + j) / 2; k++) {
if (s[k] != s[j - k + i]) {
isPalindrome = false;
break;
}
}
// If the substring is a palindrome, increment the count
if (isPalindrome) {
count++;
}
}
}
cout << count << endl; // Output the count of palindromic substrings
}
return 0;
}
Explanation:
- Include the necessary header files:
iostream
for input/output operations andstring
for handling strings. - Define the
main
function. - Read the number of test cases,
t
, from the user. - Start a loop that runs
t
times to process each test case. - Inside the loop, define a string variable
s
to store the input string for the current test case. - Initialize a variable
count
to keep track of the number of palindromic substrings. - Calculate the length of the input string
s
and store it in the variablen
. - Start a nested loop to iterate over all possible substrings of
s
. The outer loop iterates over the starting index of the substring,i
, and the inner loop iterates over the ending index of the substring,j
. - Inside the nested loops, check if the substring from index
i
to indexj
is a palindrome. To do this, iterate over the characters of the substring from indexi
to(i + j) / 2
and compare each character with its corresponding character from the end of the substring. - If the substring is a palindrome, increment the
count
variable. - After the nested loops finish, output the value of
count
for the current test case. - Repeat steps 5-11 for each test case.
- End the
main
function and return 0 to indicate successful execution of the program.
The solution uses nested loops to generate all possible substrings of the input string and checks each substring to see if it is a palindrome. If a substring is found to be a palindrome, the count is incremented. Finally, the program outputs the count for each test case.