Open In App

Remove all the palindromic words from the given sentence

Improve
Improve
Like Article
Like
Save
Share
Report

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.  

Implementation:

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*N), as we are using a loop to traverse N times and checking for palindrome which takes linear time.
Auxiliary Space: O(N), as we are using extra space for final string.

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.

Implementation:

C++




#include <iostream>
#include <vector>
#include <sstream>
 
using namespace std;
// Function to check if a word is a palindrome or not
bool isPalindrome(string word) {
    // Initialize left and right pointers for the word
    int left = 0;
    int right = word.length() - 1;
    // Check if the word is a palindrome
    while (left < right) {
        // If the characters at left and right pointers
        // are not equal, the word is not a palindrome
        if (word[left] != word[right]) {
            return false;
        }
 
        // Increment the left pointer and decrement the
        // right pointer
        left++;
        right--;
    }
 
    // If the loop has completed, the word is a
    // palindrome
    return true;
}
// Function which returns list of words that are not
// palindrome
vector<string> removePalindrome(string str) {
    // Split the string into individual words using
    // space as a separator
    vector<string> words;
    stringstream ss(str);
    string word;
    while (ss >> word) {
        words.push_back(word);
    }
 
    // Create a new vector to store the words that are not
    // palindrome
    vector<string> newList;
 
    // Iterate over all the words in the input string
    for (auto word : words) {
        // If the word is not a palindrome, add it to
        // the new vector
        if (!isPalindrome(word)) {
            newList.push_back(word);
        }
    }
 
    // Return the vector of words that are not palindrome
    return newList;
}
 
 
 
 
// Main function which executes the code
int main() {
    // Input string
    string str = "Text contains malayalam and level words";
    // Call the removePalindrome function and print the
    // result
    vector<string> result = removePalindrome(str);
    for (auto word : result) {
        cout << word << " ";
    }
    cout << endl;
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Main {
    // Function which returns list of words that are not
    // palindrome
    public static List<String>
    removePalindrome(String string)
    {
        // Split the string into individual words using
        // space as a separator
        String[] words = string.split(" ");
        // Create a new list to store the words that are not
        // palindrome
        List<String> newList = new ArrayList<>();
 
        // Iterate over all the words in the input string
        for (String word : words) {
            // If the word is not a palindrome, add it to
            // the new list
            if (!isPalindrome(word)) {
                newList.add(word);
            }
        }
 
        // Return the list of words that are not palindrome
        return newList;
    }
 
    // Function to check if a word is a palindrome or not
    public static boolean isPalindrome(String word)
    {
        // Initialize left and right pointers for the word
        int left = 0;
        int right = word.length() - 1;
        // Check if the word is a palindrome
        while (left < right) {
            // If the characters at left and right pointers
            // are not equal, the word is not a palindrome
            if (word.charAt(left) != word.charAt(right)) {
                return false;
            }
 
            // Increment the left pointer and decrement the
            // right pointer
            left++;
            right--;
        }
 
        // If the loop has completed, the word is a
        // palindrome
        return true;
    }
 
    // Main function which executes the code
    public static void main(String[] args)
    {
        // Input string
        String string
            = "Text contains malayalam and level words";
        // Call the removePalindrome function and print the
        // result
        System.out.println(removePalindrome(string));
    }
}


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))
#This code is contributed by tvsk


C#




using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
// C# code implementation of the above approach.
 
class HelloWorld {
 
    // Function to check if a word is a palindrome or not
    public static bool isPalindrome(string word) {
        // Initialize left and right pointers for the word
        int left = 0;
        int right = word.Length - 1;
        // Check if the word is a palindrome
        while (left < right) {
            // If the characters at left and right pointers
            // are not equal, the word is not a palindrome
            if (word[left] != word[right]) {
                return false;
            }
 
            // Increment the left pointer and decrement the
            // right pointer
            left++;
            right--;
        }
 
        // If the loop has completed, the word is a
        // palindrome
        return true;
    }
     
    public static List<string> removePalindrome(string str)
    {
          // Split by space and converting String to array
          string[] arr = str.Split(" ");
 
          // Initialize a new array
          List<string> newArr = new List<string> ();
 
          // Loop through the array
          for (int i = 0; i < arr.Length; i++)
        {
            // Check if the word is palindrome
            if (!isPalindrome(arr[i]))
            {
                  newArr.Add(arr[i]);
            }
          }
 
          return newArr;
    }
 
 
    static void Main() {
        string str = "Text contains malayalam and level words";
        List<string> res = removePalindrome(str);
        foreach(var x in res){
            Console.Write(x + " ");
        }
         
    }
}
 
// The code is contributed by Nidhi goel.


Javascript




<script>
     function removePalindrome(string)
    {
          // Split by space and converting String to array
          let arr = string.split(" ");
 
          // Initialize a new array
          let newArr = [];
 
          // Loop through the array
          for (let i = 0; i < arr.length; i++)
        {
            // Check if the word is palindrome
            if (arr[i] !== arr[i].split("").reverse().join(""))
            {
                  newArr.push(arr[i]);
            }
          }
 
          return newArr;
    }
 
    let string = "Text contains malayalam and level words";
    console.log(removePalindrome(string));
</script>


Output

Text contains and words

Time Complexity: O(N), as we are using a loop to traverse N times.
Auxiliary Space: O(N), as we are using extra space for newlis.



Last Updated : 03 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads