LeetCode:Reverse Words in a String III

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"

思路:题目比较简单,可以使用自带的分割方法等,这里没有使用库函数,而是使用最直接的方式进行单词翻转,关键在于找到单词的收尾。
 1 void sw(string& s, int b, int e)
 2 {
 3     char t;
 4     while (b<e)
 5     {
 6         t = s[b];
 7         s[b] = s[e];
 8         s[e] = t;
 9         ++b; --e;
10     } 
11 }
12 string reverseWords(string s) {
13     bool isw = false;
14     int len = s.length();
15     int i = 0;
16     int b;
17     while (i < len)
18     {
19         if (s[i] == ' ')
20         {
21             if (isw)
22                 sw(s, b, i-1);
23             isw = false;
24         }
25         else
26         {
27             if (!isw)
28                 b = i;
29             isw = true;
30         }
31         ++i;
32     }
33     if (isw)
34         sw(s, b, len - 1);
35     return s;
36 }

 

如果你有任何疑问或新的想法思路,欢迎在下方评论。

posted @ 2017-04-10 21:18  陆小风不写代码  阅读(116)  评论(0编辑  收藏  举报