(LeetCode) Reverse Words in a String

来源:互联网 发布:淘宝怎么买dota2装备 编辑:程序博客网 时间:2024/06/05 18:47

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 0