We are given a string and we need to reverse words of a given string
Examples:
Input : str =" geeks quiz practice code" Output : str = code practice quiz geeks Input : str = "my name is laxmi" output : str= laxmi is name my
reverse the words in the given string program
# Python code # To reverse words in a given string # input string string = "geeks quiz practice code"
# reversing words in a given string s = string.split()[:: - 1 ]
l = []
for i in s:
# apending reversed words to l
l.append(i)
# printing reverse words print ( " " .join(l))
|
code practice quiz geeks
Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string
We are given a string and we need to reverse words of a given string? Examples:
Input : str = geeks quiz practice code Output : str = code practice quiz geeks
This problem has an existing solution please refer Reverse words in a given String link. We will solve this problem in python. Given below are the steps to be followed to solve this problem.
- Separate each word in a given string using split() method of string data type in python.
- Reverse the word separated list.
- Print words of the list, in string form after joining each word with space using ” “.join() method in python.
Implementation:
# Function to reverse words of string def rev_sentence(sentence):
# first split the string into words
words = sentence.split( ' ' )
# then reverse the split string list and join using space
reverse_sentence = ' ' .join( reversed (words))
# finally return the joined string
return reverse_sentence
if __name__ = = "__main__" :
input = 'geeks quiz practice code'
print (rev_sentence( input ))
|
code practice quiz geeks
Time Complexity: O(n), where n is the length of the string
Auxiliary Space: O(n), where n is the length of the string
This solution use the same procedure but have different methods to reverse the words in string with the help backward iteration and regular expression module. Following are the steps of our approach:
- Find all the words in string with the help of re.findall() function.
- Iterate over the list in backward manner.
- Join the words in a string with the help of join() function.
# Function to reverse words of string import re
def rev_sentence(sentence):
# find all the words in sentence
words = re.findall( '\w+' , sentence)
# Backward iterate over list of words and join using space
reverse_sentence = ' ' .join(words[i] for i in range ( len (words) - 1 , - 1 , - 1 ))
# finally return the joined string
return reverse_sentence
if __name__ = = "__main__" :
input = 'geeks quiz practice code'
print (rev_sentence( input ))
|
code practice quiz geeks
Another approach to reverse the words in a given string is to use a stack. A stack is a data structure that supports push and pop operations. You can use a stack to reverse the words in a string by pushing the words onto the stack one by one and then popping them off the stack to form the reversed string.
Here is an example of how you can use a stack to reverse the words in a given string in Python:
# initializing string string = "geeks quiz practice code"
# creating an empty stack stack = []
# pushing words onto the stack for word in string.split():
stack.append(word)
# creating an empty list to store the reversed words reversed_words = []
# popping words off the stack and appending them to the list while stack:
reversed_words.append(stack.pop())
# joining the reversed words with a space reversed_string = " " .join(reversed_words)
# printing the reversed string print (reversed_string)
#This code is contributed by Edula Vinay Kumar Reddy |
code practice quiz geeks
Method:
1. The input string is split into a list of words using the split() method. By default, split() splits the string on whitespace characters (spaces, tabs, and newlines), so each word is separated into its own element of the list.
2. An empty string variable called reversed_string is initialized.
3. A for loop is used to iterate over the indices of the words list in reverse order. The loop starts from the index of the last word in the list (i.e., len(words)-1) and goes backwards to the first word (i.e., index 0). For each index, the corresponding word is appended to reversed_string, followed by a space character.
4. Finally, the extra space character at the end of reversed_string is removed using the strip() method, and the resulting string is returned.
def reverse_words(string):
# split the string into a list of words
words = string.split()
# initialize an empty string to store the reversed words
reversed_string = ''
# loop through the words in reverse order and append them to the reversed string
for i in range ( len (words) - 1 , - 1 , - 1 ):
reversed_string + = words[i] + ' '
# remove the extra space at the end of the reversed string and return it
return reversed_string.strip()
# example usage string = "geeks quiz practice code"
reversed_string = reverse_words(string)
print (reversed_string) # output: "code practice quiz geeks"
|
code practice quiz geeks
time complexity: O(n)
auxiliary space: O(n)
This approach has a time complexity of O(n) and a space complexity of O(n), where n is the length of the string.
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.