(LeetCode) Reverse Words in a String

problem :Reverse Words in a String

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

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

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.
分析:
初看此题时想起了《剑指offer》第六章面试题42:翻转单次序列vs左旋转字符串这个题。
原题:输入一个英文句子,翻转句子中单词顺序,但单词内部字符顺序不变,为简单起见,标点符号和普通字母一样处理。例如输入字符串“I am a student.”,则输出为"Student. a am I"。

原题是c实现的。
原题代码参考这个博文:
http://blog.csdn.net/sunnyyoona/article/details/17024851

而leetcode上这个题我是c++实现的。
思想:使用栈的思想实现。
定义:变量 temp,ss;temp 是获取每个单词序列,ss是获取整个翻转完成后的句子。
针对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.
第一点说明我们可以按照空格分割单词。
第二点告诉我们我们需要处理输入字符串首尾的空格字符,即剔除掉首尾的空格字符。
第三点告诉我们如果单词与单词之间有多个空格字符,我们翻转的时候需要剔除多余的,保留一个。
针对于二三点,以下代码既可以解决。
while(i>=0&&s[i] == ' ')//解决多个字符的情况
        {
            i --;
        }
        if(i<0) break;//解决首部多个字符剔除完毕后,i<0 ,即后续没有字符,需跳出循环。example:in : "   i"   out:"i".
        if(ss.length()!=0)
            ss.push_back(' ');

之后执行以下翻转思想:
1、从字符串末尾处遍历。遇到非空格的字符压入栈中,即push_back到temp中储存。遇到空格或者下标<0,即执行2。
2、将temp翻转。
3、翻转后的temp即是一个单词、追加于ss之后。
循环以上。既得翻转序列。

以下是完整代码:
class Solution {
public:
void reverseWords(string & s)
{

    string ss;
    int i = s.length()-1;
    while(i>=0)
    {
        while(i>=0&&s[i] == ' ')
        {
            i --;
        }
        if(i<0) break;
        if(ss.length()!=0)
            ss.push_back(' ');
        string temp ;
        for(;i>=0&&s[i]!=' ';i--)
            temp.push_back(s[i]);
        reverse(temp.begin(),temp.end());
        ss.append(temp);
    }
    s=ss;
}
};


已AC;


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值