翻转字符串里的单词。题目即是题意。例子,
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.
有两种corner case需要排除,一种是input前后多余的空格,一种是单词之间的多余空格。思路是先把input字符串分开成数组,再将数组reverse,最后将数组的每个元素拼接成字符串。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public String reverseWords(String s) { 3 // corner case 4 if (s == null || s.length() == 0) { 5 return s; 6 } 7 8 // normal case 9 StringBuilder sb = new StringBuilder(); 10 // trim 前后 skip 中间的回车 空格之类的东西 11 String[] words = s.trim().split("\\s+"); 12 for (int i = words.length - 1; i >= 0; i--) { 13 sb.append(words[i] + " "); 14 } 15 return sb.toString().trim(); 16 } 17 }
JavaScript实现
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 };