[LeetCode] 557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

反转字符串中的单词 III。给一个句子,请翻转句子中的所有单词。

思路是前后追击型的双指针。比较靠前的指针在遇到空格的时候就停下,开始做reverse。唯一需要注意的是在遍历完整个input string之后,需要再做一次reverse因为在前的指针只有在遇到空格的时候才会结算/reverse,但是对于最后一个单词,需要额外再处理一次。

时间O(n)

空间O(n) - char array

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         char[] input = s.toCharArray();
10         int i = 0;
11         int j = 0;
12         while (i < input.length) {
13             while (i < input.length && input[i] != ' ') {
14                 i++;
15             }
16             reverse(input, j, i - 1);
17             while (i < input.length && input[i] == ' ') {
18                 i++;
19             }
20             j = i;
21         }
22         return String.valueOf(input);
23     }
24 
25     private void reverse(char[] input, int left, int right) {
26         while (left < right) {
27             char temp = input[left];
28             input[left] = input[right];
29             input[right] = temp;
30             left++;
31             right--;
32         }
33     }
34 }

 

JavaScript实现

 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         char[] input = s.toCharArray();
10         int i = 0;
11         int j = 0;
12         while (i < input.length) {
13             while (i < input.length && input[i] != ' ') {
14                 i++;
15             }
16             reverse(input, j, i - 1);
17             while (i < input.length && input[i] == ' ') {
18                 i++;
19             }
20             j = i;
21         }
22         return String.valueOf(input);
23     }
24 
25     private void reverse(char[] input, int left, int right) {
26         while (left < right) {
27             char temp = input[left];
28             input[left] = input[right];
29             input[right] = temp;
30             left++;
31             right--;
32         }
33     }
34 }

 

相关题目

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-06-05 09:24  CNoodle  阅读(204)  评论(0编辑  收藏  举报