151. Reverse Words in a String

来源:互联网 发布:监听2121端口 编辑:程序博客网 时间:2024/06/06 01:35

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.

说来真是讽刺,楼主今天居然在面试(Microsoft On-campus)里遇到这题。因为是一面,所以题目比较简单。
面试很重要的一个环节就是在做题之前主动的提出clarification的问题,想到可能的特例,这样确定的思路才比较全面。

这题属于简单题,但在去空格这件事上有两种思路,一种就是不去管原来的空格都是什么分布,反正我们只需要把word抠出来,然后再新的string里用空格隔开就是。
代码如下:

void reverseWords(string &s) {    int len = s.length();    int i = 0;    string ans;    string word;    for (i = 0; i < len; i++) {        if (s[i] == ' ') {            if (word.length() != 0) {                if (ans.length() == 0) ans += word;                else ans = word + " " + ans;                word.clear();            }        }         else {            word.push_back(s[i]);        }    }    if (word.length() > 0 && ans.length() > 0) ans = word + " " + ans;    else ans += word;    s = ans;    return;}

因为是不断的扩充ans string, 所以运行速度并不高。第二种想法就是先把原来的空格全都保留下来,然后在生成的新string上做判断,去掉首尾空格,去掉中间重复空格。
代码:

void reverseWords(string &s) {    int len = s.length();    int i = 0;    int j = len - 1;    string ans = s;    string word;    for (i = 0; i < len; i++) {        if (s[i] == ' ') {            if (word.length() != 0) {                ans.replace(j - word.length() + 1, word.length(), word);                j = j - word.length();                word.clear();            }            ans[j--] = ' ';        }         else {            word.push_back(s[i]);            if (i == len - 1) {                ans.replace(j - word.length() + 1, word.length(), word);                j = j - word.length();                word.clear();            }        }    }    int end = -1;    int begin = -1;    for (i = 0; i < len; i++) {        if (ans[i] != ' ') {            if (begin == -1) begin = i;            end = i;        }    }    string ans2;    for (i = begin; i <= end; i++) {        if (i > begin && ans[i - 1] == ' ' && ans[i] == ' ') continue;        else ans2.push_back(ans[i]);    }    s = ans2;    return;}

第二个在速度上会快一些,因为少了很多动态内存的分配,即使是直接在built-in类型的char array 上也没有问题。总之这种问题,减少对复杂情况的分类讨论在代码构建上非常有好处。

原创粉丝点击