Reverse Words in a String

Description:

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.
思路:

         这道题就是一个简单的字符串处理的题目,题目很简单,方法很多。做这类题目最讨厌的就是单词间和整个string开头和结尾的空格,做string类题目可以先做一下预处理,把多余的空格去掉。另外一个难点就是如何精准的定位一个word。我如下的solution中做法是用一个flag表示现在是在找word的起点或是终点。flag为true表示寻到起点,为false表示寻找终点。最好还要注意最后一个单词的处理,for循环完后,如果flag为false表示最后一个单词未做处理。找到每个word 后,就放到一个stack中,最后出栈拼出最终的string.

Solution:

class Solution
{
public:
    void reverseWords(string &s)
    {
        stack<string> ss;
        bool flag=true;//Find the head of a new word if flag is "ture",else find the end of a new word
        string::iterator beg,it;
        for(it=s.begin();it!=s.end();++it)
        {
            if(flag && *it!=' ')
            {
                beg=it;
                flag=!flag;
            }
            else if(!flag && *it==' ')
            {
                string temp(beg,it);
                ss.push(temp);
                flag=!flag;
            }
        }
        if(flag == false)ss.push(string(beg,it));
        
        s="";
        while(!ss.empty())
        {
            s+=ss.top();
            ss.pop();
            if(!ss.empty())s+=" ";
        }
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值