HappyLeetcode1:Reverse Words in a String
题目描述:
题目思考:
- 建立一个数组,每个数组存储一个单词。
- 将该数组倒序输出,每输出一个单词后,紧跟着输出一个空格。
题目解题代码
Python
class Solution:
# @param s, a string
# @return a string
def reverseWords(self, s):
slist=[]
slist=s.split()
for i in range(len(slist)/2):
slist[i],slist[len(slist)-1-i]=slist[len(slist)-1-i],slist[i]
return ‘ ‘.join(slist)
C++
class Solution {
public:
void reverseWords(string &s) {
if(s.empty())
return;
//remove heading and trailing spaces
int i = 0;
while(i<s.size() && s[i] == ‘ ‘)
i++;
if(i == s.size())
{
s = "";
return;
}
int j = s.size() - 1;
while(j>=0 && s[j] == ‘ ‘)
j--;
if(j == -1)
{
s = "";
return;
}
s = s.substr(i,j - i + 1);
size_t pos = 0;
vector<string> strs;
size_t begin = 0;
while(begin < s.size())
{
pos = s.find_first_of(‘ ‘,begin);
if(pos == begin)
{
begin++;
continue;
}
else if(pos != -1)
strs.push_back(s.substr(begin,pos - begin));
else //pos == -1, the end
{
strs.push_back(s.substr(begin,s.size() - 1 - begin + 1));
break;
}
begin = pos + 1;
}
string ans;
for(int i = strs.size() - 1; i > 0; i--)
{
ans += strs[i];
ans += " ";
}
ans += strs[0];
s = ans;
}
};
题后总结
- ‘ ‘.join(slist) 堪称列表转字符串的神表达。
官网答案
One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.
We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.