首页 > 其他 > 详细

[Leetcode] Reverse Words in a String

时间:2014-03-28 23:19:08      阅读:581      评论:0      收藏:0      [点我收藏+]

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.  

 

没什么多说的,去空格看似挺麻烦,一次遍历就能搞定。注意最后的空格要特殊处理。

 

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     void reverse(string &s, int low, int high) {
 4         char tmp;
 5         while(low < high) {
 6             tmp = s[low];
 7             s[low] = s[high];
 8             s[high] = tmp;
 9             low++;
10             high--;
11         }
12     }
13     
14     void removeBlank(string &s) {
15         if (s.length() == 0) {
16             return;
17         }
18         int count = 0;
19         bool flag = false;
20         for (int i = 0; i <= s.length(); ++i) {
21             if (s[i] ==   && !flag) {
22                 count++;
23             } else if (s[i] ==   && flag) {
24                 flag = false;
25                 s[i-count] = s[i];
26             } else if (s[i] !=  ) {
27                 flag = true;
28                 s[i-count] = s[i];
29             }
30         }
31         int len = s.length() - count;
32         if (s[len-1] ==  ) {
33             s[len-1] = \0;
34             len--;
35         }
36         s.resize(len);
37     }
38 
39     void reverseWords(string &s) {
40         removeBlank(s);
41         reverse(s,0,s.length()-1);
42         int a = 0, b;
43         for (int i=0; i<=s.length();++i){
44             if(s[i]== ||s[i]==\0){
45                 b = i-1;
46                 reverse(s,a,b);
47                 a = i+1;
48             }
49         }
50         return;
51     }
52 };
bubuko.com,布布扣

 

[Leetcode] Reverse Words in a String,布布扣,bubuko.com

[Leetcode] Reverse Words in a String

原文:http://www.cnblogs.com/easonliu/p/3630617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!