LeetCode:reverse words in a string---两种方法实现

方法一:

用到了递归思想,按空格把字符串从中间分成前后两部分,分别前后两部分互换,一直递归下去,即可达到目标。

如 s = “the sky is blue” 先把s分为s1 = “the sky” s2 = “ is blue” 交换可以变为 s =  s2 + s1 = "is blue the sky"。若s2和s1也分别交换前后两部分 则s1‘ = “sky the” s2’ = “blue is”

s = s2‘ + s1’ = “blue is sky the”

代码如下:

class Solution {
public:
    void reverseWords(string &s) {
      if(s.size()!=0)
        s = reverse(s);
    }
string reverse(string s) {
eraseBlank(s);
if(s.find(" ") == s.npos || s == " " || s.size() == 0)
return s;
string::size_type position1 = 0;
string::size_type position2 = string::npos;
while(position1 <= position2)
{
position1 = s.find(" ",position1) + 1;
position2 = s.rfind(" ",position2) - 1;
}
string str1 = reverse(s.substr(position1 , s.size() - position1));
string str2 = reverse(s.substr(0 , position2 + 1));
string str3 = s.substr(position2 + 1,position1 - position2 -1);

eraseBlank(str3);
if(str3 == "")
return str1 + " " + str2;

str3 = " " + str3 + " ";
return str1 + str3 +  str2;
}


void eraseBlank(string& s)
{
while(s.find(" ") == 0 || s.size() == 0)
{
if(s == ""){
return;
}
s.erase(0,1);
}
while(s.rfind(" ") == s.size() - 1)
s.erase(s.size() - 1,1);
return;
}
};


已AC; RunTime:64ms


方法二:用桟来倒置

从后往前遍历字符串,遇到非空格字符压入桟中,遇到空格字符,将桟中的字符弹出,形成一个单词,并追加在新字符串中,遍历完后即得到要求的字符串。其中需要注意空格的处理。

代码如下:

class Solution {
public:
    void reverseWords(string &s) {
        int index = s.size();
   string strTemp = "";
   stack<char> stackReverse;
   while(index--)
   {
    if(s[index] != ' ')
    stackReverse.push(s[index]);
    else
    {
    if(stackReverse.size() == 0)
    continue;
    while(stackReverse.size() != 0)
    {
    strTemp += stackReverse.top();
    stackReverse.pop();
    }
    if(index)
    strTemp += " ";
    }
    }
    while(stackReverse.size() != 0)
    {
    strTemp += stackReverse.top();
    stackReverse.pop();
    }
    if(strTemp[strTemp.size()-1] == ' ')
    strTemp = strTemp.substr(0,strTemp.length()-1);
    s = strTemp;
      }
};


已AC; RunTime:48ms


方法二中处理空格不是很巧妙,最后需要额外判断,求大家更快更简洁的方法!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值