Search code examples
javaloopsstackqueuepalindrome

How can I print the palindrome words in a sentence? If I input "Madam Arora teaches math", it should print "Madam Arora"


class Palindrome { 
      
    // Function to check if a word is 
    // palindrome 
    static boolean checkPalin(String word) 
    { 
        int n = word.length(); 
        word = word.toLowerCase(); 
        for (int i=0; i<n; i++,n--) 
           if (word.charAt(i) != word.charAt(n - 1)) 
              return false;        
        return true; 
    } 
      
    // Function to count palindrome words 
    static int countPalin(String str) 
    {         
        // to check last word for palindrome 
        str = str + " "; 
          
        // to store each word 
        String word = ""; 
        int count = 0; 
        for (int i = 0; i < str.length(); i++) 
        { 
            char ch = str.charAt(i); 
              
            // extracting each word 
            if (ch != ' ') 
                word = word + ch; 
            else { 
                if (checkPalin(word)) 
                    count++; 
                word = ""; 
            } 
        } 
          
        return count; 
    } 
      
    // Driver code 
    public static void main(String args[]) 
    { 
        System.out.println(countPalin("Madam "
                  + "Arora teaches malayalam")); 
                    
        System.out.println(countPalin("Nitin "
                        + "speaks malayalam")); 
    }
}

I only know how to count the number. How can I run through a loop and check every word if it is a palindrome? Can you help me with a method that checks a word and a method that checks a sentence if there are palindrome words? I must use Stacks and Queues. I have done the push, add, remove, dequeue, but I can't check if the input is a sentence.


Solution

  • You need to change only this part

    if (checkPalin(word)) 
    { 
         OutPut =  OutPut + word;
     }
    

    after for loop return OutPut.