53 翻转字符串

原题网址:http://www.lintcode.com/zh-cn/problem/reverse-words-in-a-string/

给定一个字符串,逐个翻转字符串中的每个单词。

说明

 

  • 单词的构成:无空格字母构成一个单词
  • 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
  • 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个

 

样例
给出s = "the sky is blue",返回"blue is sky the"
 
 方法一:
 1 class Solution {
 2 public:
 3     /*
 4      * @param s: A string
 5      * @return: A string
 6      */
 7     string reverseWords(string &s) {
 8         // write your code here
 9         if (s.empty())
10     {
11         return s;
12     }
13     int size=s.size();
14     string word,line;
15     line.resize(0);
16     int begin=size-1,end=size-1;
17     int i=size-1;
18     
19     while(i>=0)  //从后向前寻找单词;
20     {
21         while(i>=0&&s[i]==' ') //遇到空格跳过;
22         {
23             begin--;
24             end--;
25             i--;
26         }
27         while(i>=0&&s[i]!=' ')  //遇到非空格字符,i与begin前移;
28         {
29             begin--;
30             i--;
31         }
32         word.resize(0);
33         for (int j=begin+1;j<=end;j++) //注意索引范围;
34         {
35             word.append(1,s[j]);
36         }
37         
38 
39         line=line+word+" "; //注意最后+的空格应是字符串格式;
40         end=begin;
41     }
42     //尾部空格处理;
44     while(line.size()!=0)
45     {
46         if (line[line.size()-1]==' ')
47         {
48             line.erase(line.size()-1,1);
49         }
50         else
51         {
52             break;
53         }
54     }
55 
56     return line;
57     }
58 };

方法二:

 1 class Solution {
 2 public:
 3     /*
 4      * @param s: A string
 5      * @return: A string
 6      */
 7     string reverseWords(string &s) {
 8         // write your code here
 9         if (s.empty())
10     {
11         return s;
12     }
13     int size=s.size();
14     reverse(s.begin(),s.end());  //翻转整个字符串;
15     int index=0; //新字符串索引;
16     for (int i=0;i<size;i++)//遍历,逐个翻转单词;
17     {
18         if (s[i]!=' ')
19         {
20             if (index!=0)//index不为0,说明遍历到的不是第一个单词,要在该单词前加空格;
21             {
22                 s[index++]=' ';
23             }
24             int j=i;
25             while(j<size&&s[j]!=' ')
26             {
27                 s[index++]=s[j++];
28             }
29             reverse(s.begin()+index-(j-i),s.begin()+index);//翻转新获得的单词;
30             i=j;  //避免重复遍历,继续向下循环(应注意此时的s[j]为空格或者超出范围);
31         }
32     }
33     s.resize(index);//实际上新串有效索引到index-1;
34     return s;
35     }
36 };

 

 
 
参考:
c++ append用法     
https://blog.csdn.net/zwy1258432405/article/details/77416101    第二种方法未消除尾部空格
posted @ 2018-03-26 10:20  eeeeeeee鹅  阅读(235)  评论(0编辑  收藏  举报