您的位置:首页 > 其它

Leetcode 151题 Reverse Words in a String

2014-05-16 18:24 302 查看
时间:2014.05.10

地点:基地

心情:准备刷下Leetcode题了,就从第151题开始吧

------------------------------------------------------------------------------------------

一、题目


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.

------------------------------------------------------------------------------------------

二、思路

题目要求正常处理字符串反转的同时还能能处理字符串首尾或中间多余的空格。

1.将字符串从后往前遍历,每次遍历前都为了剔除空格,从当前位置往前找,直到不是空格为止,停止变化索引。

2.继续将索引向前移动,直到遇到空格为止,这过程中遍历的字符都是属于一个单词中的。

3.重复上面两个过程,直到字符串的字符全部遍历完。

------------------------------------------------------------------------------------------

三、技巧

1.由于我们从后往前遍历,每捕获到一个完整的单词,我们均将它在反转得到单词的正序追加到结果中

2.单词与单词之间还需要有一个空格,于是我们在存储捕获单词的临时字符串中首先初始化开始第一个字符为空格,反转后它将被变换到单词尾。

-----------------------------------------------------------------------------------------

四、AC源码

class Solution {
public:
    void reverseWords(string &s) {
        string result_str = "",temp_str = "";
		for (int i = s.length()-1; i >= 0; --i)
		{
			while ((i >= 0) && (' ' == s[i]))
				--i;
			temp_str = "";
			if (i >= 0)
				temp_str.push_back(' ');
			while ((i>=0)&&(' '!=s[i]))
				temp_str.push_back(s[i--]);
			reverse(temp_str.begin(), temp_str.end());
			result_str.append(temp_str);
		}
		s = result_str;
		if (!s.empty())
			s.pop_back();
	}
};
-----------------------------------------------------------------------------------------

五、几个需要注意的地方

1.输出结果最后不能有空格

2.边界处理,比如输入长度为0的字符串或者全是空格的字符串
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: