Given an input string, reverse the string word by word.
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.
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up:
For C programmers, try to solve it in-place in O(1) extra space.
翻转字符串里的单词。题目即是题意。有两种corner case需要排除,一种是input前后多余的空格,一种是单词之间的多余空格。思路是先把input字符串分开成数组,再将数组reverse,最后将数组的每个元素拼接成字符串。
时间O(n)
空间O(n)
Java实现 - 正则表达
"s" is a regex class for any kind of whitespace (space, tab, newline, etc). Since Java uses "" as an escape character in strings (e.g. for newlines: " "), we need to escape the escape character ;-) So it becomes "\s". The "+" means one or more of them.
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 }
Java拼接实现
这种思路是trim完input之后,从后往前开始遍历input,用双指针卡住单词。先移动其中一个指针,当遇到空格的时候就需要截取单词了;将单词加入结果集之后记得要跳过单词之间的空格。
1 class Solution { 2 public String reverseWords(String s) { 3 s = s.trim(); // 删除首尾空格 4 int j = s.length() - 1; 5 int i = j; 6 StringBuilder res = new StringBuilder(); 7 while (i >= 0) { 8 while (i >= 0 && s.charAt(i) != ' ') { 9 i--; // 搜索首个空格 10 } 11 res.append(s.substring(i + 1, j + 1) + " "); // 添加单词 12 while (i >= 0 && s.charAt(i) == ' ') { 13 i--; // 跳过单词间空格 14 } 15 j = i; // j 指向下个单词的尾字符 16 } 17 return res.toString().trim(); // 转化为字符串并返回 18 } 19 }
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 };
相关题目
151. Reverse Words in a String
186. Reverse Words in a String II