LeetCode151—Reverse Words in a String

不念不忘少年蓝@ 2022-07-16 09:16 295阅读 0赞

原题

原题链接

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

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

分析

两次翻转,句子要翻转,句子里的单词也要翻转。

此题还有一些陷阱,比如前后导的空格,单词中间多余的空格等等。

其实有个比较简单的做法是用stringstream,把句子中的单词保存到vector里面,然后将vector中的每个单词逆序,最后再从后往前拼接起来。这个办法有点像java中trimsplit,很可惜好像C++并没有这样的函数,只能麻烦一点的做了。

不过还有一个更加朴素的办法:
1.处理空格(前后导和中间多余)
2.字符串逆序
3.字符串中单词逆序

思路差不多,写起来可能会麻烦一点,尤其是处理空格那一部分。

代码

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5. class Solution {
  6. private:
  7. bool flag;
  8. void removeSpace(string &s)
  9. {
  10. int i=0;
  11. int j=s.size()-1;
  12. while(s[i]==' ')
  13. {
  14. ++i;
  15. }
  16. while(s[j]==' ')
  17. {
  18. --j;
  19. }
  20. if(i>=s.size())
  21. {
  22. flag=true;
  23. return;
  24. }
  25. string tmp(s.begin()+i,s.end()-(s.size()-j)+1);
  26. s=tmp;
  27. for(int k=0;k<s.size();k++)
  28. {
  29. if(s[k]==' ')
  30. {
  31. int t=k+1;
  32. while(s[t]==' ')
  33. {
  34. s.erase(s.begin()+t);
  35. }
  36. // k=t;
  37. }
  38. }
  39. }
  40. void reverseSentense(string &s)
  41. {
  42. string tmp(s.rbegin(),s.rend());
  43. s=tmp;
  44. }
  45. void reverseWord(string &s)
  46. {
  47. int start=0;
  48. int end;
  49. for(int i=0;i<s.size();i++)
  50. {
  51. if(s[i]==' ')
  52. {
  53. end=i-1;
  54. while(start<end)
  55. {
  56. swap(s[start++],s[end--]);
  57. }
  58. start=i+1;
  59. }
  60. if(i==s.size()-1)
  61. {
  62. end=i;
  63. while(start<end)
  64. {
  65. swap(s[start++],s[end--]);
  66. }
  67. }
  68. }
  69. }
  70. public:
  71. void reverseWords(string &s) {
  72. flag=false;
  73. removeSpace(s);
  74. if(flag)
  75. {
  76. string tmp;
  77. s=tmp;
  78. return ;
  79. }
  80. reverseSentense(s);
  81. reverseWord(s);
  82. }
  83. };
  84. int main()
  85. {
  86. Solution test;
  87. string s= " a b c d e ";
  88. test.reverseWords(s);
  89. cout<<s<<endl;
  90. return 0;
  91. }

——-2016 10/14补充———

使用stringstream分割单词

方法参见:C++ string流简介

  1. class Solution {
  2. public:
  3. void reverseWords(string &s) {
  4. if(s.empty())
  5. return ;
  6. stringstream ss(s);
  7. vector<string> words;
  8. string word;
  9. while(ss>>word)
  10. words.push_back(word+' ');
  11. if(!words.empty())
  12. {
  13. s.clear();
  14. for(int i=words.size()-1;i>=0;i--)
  15. {
  16. s+=words[i];
  17. }
  18. s.pop_back();
  19. }
  20. else
  21. {
  22. string tmp;
  23. s=tmp;
  24. }
  25. }
  26. };

发表评论

表情:
评论列表 (有 0 条评论,295人围观)

还没有评论,来说两句吧...

相关阅读