Skip to content
Related Articles

Related Articles

Improve Article

Remove all the palindromic words from the given sentence

  • Difficulty Level : Basic
  • Last Updated : 20 May, 2021

Given a sentence str. The problem is to remove all the palindromic words from the given sentence.
Examples: 

Input : str = "Text contains malayalam and level words"
Output : Text contains and words

Input : str = "abc bcd"
Output : abc bcd

Approach: One by one extract all the words. Check if the current word is not a palindrome then add it to the final string. 
Algorithm:

removePalinWords(str, n)
    Initialize final_str = "", word = ""
    str = str + " "
    
    for i = 0 to n-1
        if str[i] != ' ', then
        word = word + str[i]
    else 
        if (!(isPalindrome(word)), then
            final_str += word + " "
        word = ""
            
    return final_str

isPalindrome() function is used to check whether the given string is palindrome or not. Refer this post.  

C++




// C++ implementation to remove all the
// palindromic words from the given sentence
#include <bits/stdc++.h>
using namespace std;
 
// function to check if 'str' is palindrome
bool isPalindrome(string str) {
  int i = 0, j = str.size() - 1;
 
  // traversing from both the ends
  while (i < j)
 
    // not palindrome
    if (str[i++] != str[j--])
      return false;
 
  // palindrome
  return true;
}
 
// function to remove all the palindromic words
// from the given sentence
string removePalinWords(string str) {
 
  // 'final_str' to store the final string and
  // 'word' to one by one store each word of 'str'
  string final_str = "", word = "";
 
  // add space at the end of 'str'
  str = str + " ";
  int n = str.size();
 
  // traversing 'str'
  for (int i = 0; i < n; i++) {
 
    // accumulating characters of the current word
    if (str[i] != ' ')
      word = word + str[i];
 
    else {
 
      // if 'word' is not palindrome then a
      // add it to 'final_str'
      if (!(isPalindrome(word)))
        final_str += word + " ";
 
      // reset
      word = "";
    }
  }
 
  // required final string
  return final_str;
}
 
// Driver program to test above
int main() {
  string str = "Text contains malayalam and level words";
  cout << removePalinWords(str);
  return 0;
}

Java




// Java implementation to remove all the
// palindromic words from the given sentence
 
class GFG
{
    // function to check if 'str' is palindrome
    static boolean isPalindrome(String str)
    {
        int i = 0, j = str.length() - 1;
         
        // traversing from both the ends
        while (i < j)
        {
            // not palindrome
            if (str.charAt(i++) != str.charAt(j--))
            return false;
        }
        // palindrome
        return true;
    }
     
    // function to remove all the palindromic words
    // from the given sentence
    static String removePalinWords(String str)
    {
     
        // 'final_str' to store the final string and
        // 'word' to one by one store each word of 'str'
        String final_str = "", word = "";
         
        // add space at the end of 'str'
        str = str + " ";
        int n = str.length();
         
        // traversing 'str'
        for (int i = 0; i < n; i++)
        {
         
            // accumulating characters of the current word
            if (str.charAt(i) != ' ')
            word = word + str.charAt(i);
         
            else
            {
         
                // if 'word' is not palindrome then a
                // add it to 'final_str'
                if (!(isPalindrome(word)))
                    final_str += word + " ";
             
                // reset
                word = "";
            }
        }
         
        // required final string
        return final_str;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String str = "Text contains malayalam and level words";
    System.out.print(removePalinWords(str));
    }
}
 
// This code is contributed by Anant Agarwal.

Python3




# Python3 implementation to remove all the
# palindromic words from the given sentence
 
# function to check if 'str' is palindrome
def isPalindrome(string) :
    i = 0; j = len(string) - 1;
 
    # traversing from both the ends
    while (i < j) :
     
        # not palindrome
        if (string[i] != string[j]) :
            return False;
        i += 1;
        j -= 1;
     
    # palindrome
    return True;
 
# function to remove all the palindromic words
# from the given sentence
def removePalinWords(string) :
 
    # 'final_str' to store the final string and
    # 'word' to one by one store each word of 'str'
    final_str = ""; word = "";
     
    # add space at the end of 'str'
    string = string + " ";
    n = len(string);
     
    # traversing 'str'
    for i in range(n) :
     
        # accumulating characters of the current word
        if (string[i] != ' ') :
            word = word + string[i];
     
        else :
     
            # if 'word' is not palindrome then a
            # add it to 'final_str'
            if (not (isPalindrome(word))) :
                final_str += word + " ";
         
            # reset
            word = "";
     
    # required final string
    return final_str;
     
# Driver Code
if __name__ == "__main__" :
     
    string = "Text contains malayalam and level words";
    print(removePalinWords(string));
 
# This code is contributed by AnkitRai01

C#




// C# implementation to remove all the
// palindromic words from the given sentence
using System;
 
class GFG {
     
    // function to check if 'str' is
    // palindrome
    static bool isPalindrome(string str)
    {
        int i = 0, j = str.Length - 1;
         
        // traversing from both the ends
        while (i < j)
        {
             
            // not palindrome
            if (str[i++] != str[j--])
            return false;
        }
         
        // palindrome
        return true;
    }
     
    // function to remove all the
    // palindromic words from the
    // given sentence
    static String removePalinWords(string str)
    {
     
        // 'final_str' to store the final
        // string and 'word' to one by one
        // store each word of 'str'
        string final_str = "", word = "";
         
        // add space at the end of 'str'
        str = str + " ";
        int n = str.Length;
         
        // traversing 'str'
        for (int i = 0; i < n; i++)
        {
         
            // accumulating characters of
            // the current word
            if (str[i] != ' ')
                word = word + str[i];
            else
            {
         
                // if 'word' is not palindrome
                // then a add it to 'final_str'
                if (!(isPalindrome(word)))
                    final_str += word + " ";
         
                // reset
                word = "";
            }
        }
         
        // required final string
        return final_str;
    }
     
    // Driver code
    public static void Main ()
    {
        string str = "Text contains malayalam "
                           + "and level words";
        Console.WriteLine(removePalinWords(str));
    }
}
 
// This code is contributed by vt_m.

Javascript




<script>
 
// Javascript implementation to remove all the
// palindromic words from the given sentence
 
// function to check if 'str' is palindrome
function isPalindrome(str) {
  var i = 0, j = str.length - 1;
 
  // traversing from both the ends
  while (i < j)
 
    // not palindrome
    if (str[i++] != str[j--])
      return false;
 
  // palindrome
  return true;
}
 
// function to remove all the palindromic words
// from the given sentence
function removePalinWords(str) {
 
  // 'final_str' to store the final string and
  // 'word' to one by one store each word of 'str'
  var final_str = "", word = "";
 
  // add space at the end of 'str'
  str = str + " ";
  var n = str.length;
 
  // traversing 'str'
  for (var i = 0; i < n; i++) {
 
    // accumulating characters of the current word
    if (str[i] != ' ')
      word = word + str[i];
 
    else {
 
      // if 'word' is not palindrome then a
      // add it to 'final_str'
      if (!(isPalindrome(word)))
        final_str += word + " ";
 
      // reset
      word = "";
    }
  }
 
  // required final string
  return final_str;
}
 
// Driver program to test above
var str = "Text contains malayalam and level words";
document.write( removePalinWords(str));
 
// This code is contributed by itsok.
</script>
Output
Text contains and words 

Time Complexity: O(n). 



Method 2:Using Built in python functions:

  • As all the words in a sentence are separated by spaces.
  • We have to split the sentence by spaces using split().
  • We split all the words by spaces and store them in a list.
  • loop till number of words in list.
  • Take a new list and append non palindromic words.
  • print newlist.

Below is the implementation

Python3




# Python program for the above approach
 
# Function which returns last word
def removePalindrome(string):
 
    # Split by space and converting
    # String to list and
    lis = list(string.split(" "))
 
    # length of list
    length = len(lis)
     
    # Taking new list
    newlis = []
     
    # loop till length of list
    for i in range(length):
       
        # check if the word is palindrome
        if(lis[i] != lis[i][::-1]):
            newlis.append(lis[i])
 
    return newlis
 
 
# Driver code
string = "Text contains malayalam and level words"
print(*removePalindrome(string))
Output
Text contains and words

Time Complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :