Thursday, April 1, 2021

Published April 01, 2021 by Anonymous with 0 comment

Modify a sentence by reversing order of occurrences of all Palindrome Words

Modify a sentence by reversing order of occurrences of all Palindrome Words

Given a string S representing a sentence, the task is to reverse the order of all palindromic words present in the sentence.

Examples:

Input: S = “mom and dad went to eye hospital”
Output: eye and dad went to mom hospital
Explanation: All palindromic words present in the string are “mom”, “dad” and “eye, in the order of their occurrence. Reversing the order of their occurrence generates the sequence {“eye”, “dad”, “mom”}. Therefore, the modified string is “eye and dad went to mom hospital”.

Input : S = “wow it is next level”
Output: level it is wow.

Approach: Follow the steps below to solve the problem:

Below is the implementation of the above approach:

Python3

  

def palindrome(string):

    

    if(string == string[::-1]):

        return True

    else:

        return False

  

def printReverse(sentence):

    

    

    newlist = []

      

    

    lis = list(sentence.split())

      

    

    for i in lis:

        

        

        if(palindrome(i)):

            

              

            newlist.append(i)

  

    

    newlist.reverse()

      

    j = 0

      

    

    for i in range(len(lis)):

        

        

        if(palindrome(lis[i])):

            

            

            lis[i] = newlist[j]

              

            

            j = j + 1

  

    

    for i in lis:

        print(i, end =" ")

  

  

  

sentence = "mom and dad went to eye hospital"

printReverse(sentence)

Output:
eye and dad went to mom hospital

Time Complexity: O(N)
Auxiliary Space: O(1)


Let's block ads! (Why?)


Original page link

Best Cool Tech Gadgets

Top favorite technology gadgets
      edit

0 comments:

Post a Comment