VOOZH about

URL: https://www.geeksforgeeks.org/dsa/java-program-count-number-palindrome-words-sentence/

⇱ Count palindrome words in a sentence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count palindrome words in a sentence

Last Updated : 12 Jul, 2025

Given a string str and the task is to count palindrome words present in the string str.

Examples: 

Input : Madam Arora teaches malayalam
Output : 3
The string contains three palindrome words (i.e.,
Madam, Arora, malayalam) so the count is three.

Input : Nitin speaks malayalam
Output : 2
The string contains two palindrome words (i.e.,
Nitin, malayalam) so the count is two.

Method 1:
countPalin() function counts the number of palindrome words by extracting every word of the string and passing it to checkPalin() function. An extra space is added in the original string to extract last word. 
checkPalin() function check the word palindrome. It returns 1 if word is palindrome else returns 0. It makes sure that empty strings are not counted as palindrome as the user may enter more than one spaces in between or at the beginning of the string. 
 


Output: 
3
2

 

Time Complexity: O(n2), where n is the size of the given string.
Auxiliary Space: O(n), where n is the size of the given string.
 

-5HChTA0ME
 

Comment
Article Tags: