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:

  1. Include the necessary header files: iostream for input/output operations and string for handling strings.
  2. Define the main function.
  3. Read the number of test cases, t, from the user.
  4. Start a loop that runs t times to process each test case.
  5. Inside the loop, define a string variable s to store the input string for the current test case.
  6. Initialize a variable count to keep track of the number of palindromic substrings.
  7. Calculate the length of the input string s and store it in the variable n.
  8. 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.
  9. Inside the nested loops, check if the substring from index i to index j is a palindrome. To do this, iterate over the characters of the substring from index i to (i + j) / 2 and compare each character with its corresponding character from the end of the substring.
  10. If the substring is a palindrome, increment the count variable.
  11. After the nested loops finish, output the value of count for the current test case.
  12. Repeat steps 5-11 for each test case.
  13. 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.