Created
August 9, 2015 19:24
-
-
Save viveksyngh/8a523c244907af445aa1 to your computer and use it in GitHub Desktop.
Reverse a string Word by Word
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| __author__ = 'Vivek' | |
| #reverse the string word by word. | |
| def reverseWords(A): | |
| """ | |
| Reverse the string word by word, removes leading and trailing spaces, | |
| :param: string to be reversed | |
| :return: reversed string word by word | |
| """ | |
| curWord = '' | |
| listOfWords = [] | |
| for char in A : | |
| if char != ' ' : | |
| curWord += char | |
| else : | |
| if curWord != '' : | |
| listOfWords.append(curWord) | |
| curWord = '' | |
| if curWord != '' : | |
| listOfWords.append(curWord) | |
| listOfWords.reverse() | |
| return " ".join(word for word in listOfWords) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment