[LeetCode] 151. Reverse Words in a String

Flip words in strings. That topic is still on. example,

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

There are two corner case needs to be excluded, one is extra spaces before and after the input, one is extra spaces between words. The idea is first split into an array of input string, then the Reverse array, each element of the array and finally assembled into a string.

Time O (n)

Space O (n)

Java implementation

. 1  class Solution {
 2      public String reverseWords (S String) {
 . 3          // corner Case 
. 4          IF (S == null || s.length () == 0 ) {
 . 5              return S;
 . 6          }
 . 7  
. 8          // Normal Case 
. 9          SB = the StringBuilder new new the StringBuilder ();
 10          // longitudinal trim intermediate spaces or carriage returns skip things 
. 11          String [] = s.trim words () Split ( "\\ S +." );
 12 is          for ( int I = words.length -. 1; I> = 0; i-- ) {
13             sb.append(words[i] + " ");
14         }
15         return sb.toString().trim();
16     }
17 }

 

JavaScript implementation

 1 /**
 2  * @param {string} s
 3  * @return {string}
 4  */
 5 var reverseWords = function (s) {
 6     return s
 7         .split(' ')               //create an array of words separated based by spaces
 8         .filter(string => string) //remove empty strings to take care of extra whitespace
 9         .reverse()                //reverse the array of words
10         .join(' ');               //join the words back together with spaces inbetween
11 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12556557.html