[LeetCode] 151. Reverse Words in a String

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

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

Example 2:

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

Example 3:

Input: s = "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.

Constraints:

  • 1 <= s.length <= 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.
  • There is at least one word in s.

Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?

翻转字符串中的单词。

给你一个字符串 s ,请你反转字符串中 单词 的顺序。

单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。

返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。

注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-words-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意不难理解,我感觉这道题就是要考察代码熟练程度的。

我们要对 input 做预处理,一种情况是去掉 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: "\n"), 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         // corner case
 4         if (s == null || s.length() == 0) {
 5             return s;
 6         }
 7         
 8         // normal case
 9         // 去掉input边缘无效的空格
10         // " test   "
11         s = s.trim();
12         StringBuilder sb = new StringBuilder();
13         // 卡住每个单词的左右指针
14         int start = s.length() - 1;
15         int end = start;
16         while (start >= 0) {
17             // 未遇到空格之前,左指针一直往左走
18             while (start >= 0 && s.charAt(start) != ' ') {
19                 start--;
20             }
21             // 卡住单词,注意subtring是左闭右开的
22             String word = s.substring(start + 1, end + 1);
23             sb.append(word);
24             sb.append(' ');
25             // 把左右指针移动到下一个不是空格的位置上接着找下一个单词
26             while (start >= 0 && s.charAt(start) == ' ') {
27                 start--;
28             }
29             end = start;
30         }
31         return sb.toString().trim();
32     }
33 }

 

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

344. Reverse String

541. Reverse String II

557. Reverse Words in a String III

LeetCode 题目总结

posted @ 2020-03-24 05:19  CNoodle  阅读(543)  评论(0编辑  收藏  举报