Tag Archives: ISC 2013

Display and count palindromic words in a sentence in Java

A palindrome is a word that may be read the same way in either direction. Accept a sentence in UPPER CASE which is terminated by either “.”, “?”, or “!”. Each word of the sentence is separated by a single blank space.
Perform the following tasks:
a) display the count of palindromic words in the sentence.
b) Display the palindromic words in the sentence.

Example of palindromic words:

MADAM, ARORA, NOON

Test your program with the sample data and some random data:

Example 1

   INPUT   :   MOM AND DAD ARE COMING AT NOON
   OUTPUT  :   MOM DAD NOON
               NUMBER OF PALINDROMIC WORDS : 3

Example 2

   INPUT   :  HOW ARE YOU?
   OUTPUT  :  NO PALINDROMIC WORDS

The above problem on palindromic words was asked in the ISC Computer Science Practical in the year 2013. The problem implementing the palindromic words and the count of palindromic words is as follows:

import java.util.*;
class Palindrome{
	public static void main(String args[]){
		Scanner sc= new Scanner(System.in);
		System.out.println("INPUT:\t");
		String str;
		int count=0;
		str=sc.nextLine();
		str=str.replace("."," ");
		str=str.replace("?"," ");
		str=str.replace("!"," ");
		String answer="", ar[]= str.split(" ");
		for(int i=0;i < ar.length;i++){
			if(isPalindrome(ar[i])){
				count++;
				answer += ar[i] + " ";
			}
		}
		System.out.println("OUTPUT:\t\t"+answer+"\nNUMBER OF PALINDROMIC WORDS: "+count);
	}
	public static boolean isPalindrome(String str){
		char ch;
		int len=str.length(),half=len/2;
		for(int i=0;i < half;i++){
			if(str.charAt(i)!=str.charAt(len-i-1)) return false;
		}
		return true;
	}
}

In the above program on palindromic words the use of split() function defined in the String class deserves a special mention. The split() function will split the string on which it’s invoked into an array based on the delimiter passed as an argument. In the above program on palindromic words the delimiter is the space character. This will return an array ar such that each element of an array stores one word of the string. Also note that for increasing the efficiency of the code the isPalindrome() function is testing the ith character of the string str with the length-i-1th character of the string. This way the loop only runs half the length of the original string and false is returned as soon as the first mismatch is detected. The method of reversing the string and comparing the reversed string is a bit slower because the loops runs for the entire length of the string irrespective of the whether or not it’s a palindrome, even it the mismatch is found at the first character.