Write a Python program to count number of substrings with same first and last characters of a given string


The program takes a string as input from the user and counts the number of palindromic substrings present in the input string. A substring is a palindrome if it reads the same forwards as it does backwards. The algorithm to count the number of palindromic substrings in the input string is as follows:

  • Initialize a variable res to 0.
  • Use nested loops to consider all substrings one by one.
  • The outer loop will iterate through the length of the string, starting from the first character, and the inner loop will start from the outer loop variable i and will keep iterating until the end of the string.
  • For each iteration, check if the first and last characters of the current substring are equal. If they are, increase the count of palindromic substrings by 1.
  • Return the count of palindromic substrings after the loop ends.

In the end, the program will print the number of palindromic substrings found in the input string

Source Code

str = input("Enter The String :")
res = 0
n = len(str)
for i in range(n): 
	for j in range(i, n): 
		if (str[i] == str[j]): 
			res = res + 1
print(res)

Output

Enter The String :Python
6



Example Programs