标签:style blog class code c color
时间:2014.05.10
地点:基地
心情:准备刷下Leetcode题了,就从第151题开始吧
------------------------------------------------------------------------------------------
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
------------------------------------------------------------------------------------------
题目要求正常处理字符串反转的同时还能能处理字符串首尾或中间多余的空格。
1.将字符串从后往前遍历,每次遍历前都为了剔除空格,从当前位置往前找,直到不是空格为止,停止变化索引。
2.继续将索引向前移动,直到遇到空格为止,这过程中遍历的字符都是属于一个单词中的。
3.重复上面两个过程,直到字符串的字符全部遍历完。
------------------------------------------------------------------------------------------
1.由于我们从后往前遍历,每捕获到一个完整的单词,我们均将它在反转得到单词的正序追加到结果中
2.单词与单词之间还需要有一个空格,于是我们在存储捕获单词的临时字符串中首先初始化开始第一个字符为空格,反转后它将被变换到单词尾。
-----------------------------------------------------------------------------------------
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();
}
};-----------------------------------------------------------------------------------------
Leetcode 151题 Reverse Words in a String,布布扣,bubuko.com
Leetcode 151题 Reverse Words in a String
标签:style blog class code c color
原文地址:http://blog.csdn.net/u012333003/article/details/25991025