Reverse Words in a String - LeetCode 151

来源:互联网 发布:杭州行知小学招聘 编辑:程序博客网 时间:2024/04/29 19:15
题目描述:
Given an input string, reverse the string word by word.

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

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.
Hide Tags String

分析:
要将一个字符串中的单词逆序(但单词本身是有序的)输出,其实问题转化成从字符串末尾开始,找出所有单词。
需要注意几点:字符串中可能会出现多个连续的空格;首尾也可以出现空格;或者是空串。
如何得到单词word?
从后往前遍历字符串,从第一个非空格元素开始到下一个空格或下标越界,将字符插入word首部,这样就得到一个正确的单词,然后将单词加入ss

(存储结果的字符串)尾部。继续循环处理,直到下标越界;
最后将ss赋值给s即可。

以下是C++实现代码:

/**/////////////12ms//*/class Solution {public:    void reverseWords(string &s) {       int len = s.size();int i = len - 1;string ss; while(i >= 0){while(i >= 0 && s[i] == ' ')i--;if(i < 0)break;if(ss.size()!= 0)ss.push_back(' '); // 在单词间添加一个空格string word;while(i >=0 && s[i] != ' ') // 将字符插入word前端,这样就直接得到顺序的单词,直到遇到空格或下标越界{word.insert(0,1,s[i]);i--;}ss.append(word); //将新得到的单词插入ss尾部}s =ss; //更新s    }};


0 0
原创粉丝点击