Reverse Words in a String

来源:互联网 发布:linux 用终端打开文件 编辑:程序博客网 时间:2024/06/05 15:49

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

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

click to show 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.
这题感觉不难啊,但是ac率好低,可能是空格的情况需要仔细考虑吧。

思路:从s的尾部往头遍历,遇到空格就继续前进;不是空格,再设置一个指针往前走,直到空格。然后把这段字符串反转下就下。


void reverseWords(string &s){    int len = s.size();    int i=len-1,j;    string result="",tmp="";    while(i >= 0)    {        if(s[i]!=' ')        {            tmp += s[i];            for(j=i-1; j>=0&&s[j]!=' '; j--)                tmp += s[j];            reverse(tmp.begin(), tmp.end());            i=j;            result += tmp + " ";            tmp="";        }        if(s[i]==' ')            i--;    }    int newlen=result.size();    if(newlen==0)        s="";    else    {        result.erase(newlen-1);        s=result;    }}


0 0
原创粉丝点击