Created
September 11, 2018 03:27
-
-
Save yokolet/b8d85288f5d50903e7bbc2ea90c17c40 to your computer and use it in GitHub Desktop.
Reverse Words in a String
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
| """ | |
| Description: | |
| Given an input string , reverse the string word by word. | |
| A word is defined as a sequence of non-space characters. | |
| The input string does not contain leading or trailing spaces. | |
| The words are always separated by a single space. | |
| Example: | |
| Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] | |
| Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] | |
| """ | |
| def reverseWords(s): | |
| """ | |
| :type str: List[str] | |
| :rtype: void Do not return anything, modify str in-place instead. | |
| """ | |
| n = len(s) | |
| s.reverse() | |
| spaces = [idx for (idx, c) in zip(range(n), s) if c == ' '] | |
| start = 0 | |
| for i in spaces: | |
| s[start:i] = s[start:i][::-1] | |
| start = i + 1 | |
| s[start:] = s[start:][::-1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment