Hello_Motty

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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.

题意:把输入的字符串单词的顺序不变,单词中字母顺序逆置,测试中所给的字符串中不会有两个相连的空格。

基本思路:

1. 查单词,把从开始到空格、空格之间和空格到结束之间的单词分别保存在一个字符串数组中,当结束时,把字符串数组中的每个单词倒置,然后按顺序输出中间插入空格。

这种方法虽然条理清晰,但是用了大量的额外空间,而且相当于要遍历三次,所以不推荐使用。

2. 下面这种方式没有使用额外空间就对每个单词进行头尾交换。代码如下

 1 char* reverseWords(char* s) {
 2     char *beg = s;
 3     char *end = s;
 4     char temp = 0;
 5     while(*beg != '\0')
 6     {
 7         if(*beg == ' '){
 8             ++beg;
 9             ++end;
10         }else if(*end == '\0' || *end == ' ')
11         {
12             char *ps = beg, *pe = end-1;
13             while(ps <pe){
14                 temp = *ps;
15                 *ps = *pe;
16                 *pe = temp;
17                 ps++;
18                 pe--;
19             }
20             beg = end;
21         }else
22             end++;
23     }
24     return s;
25 }

写的简洁一点就是

 1 class Solution {
 2 public:
 3     string reverseWords(string s) {
 4         size_t front = 0;
 5         for(int i = 0; i <= s.length(); ++i)
 6             if(i == s.length() || s[i] == 0x20){
 7                 reverse(&s[front], &s[i]);
 8                 front = i + 1;
 9             }        
10         return s;
11     }
12 };

使用c++的reverse函数而不自定义反转函数,关于reverse函数:http://www.cplusplus.com/reference/algorithm/reverse/

 

posted on 2017-08-18 20:48  Hello_Motty  阅读(189)  评论(0编辑  收藏  举报