标签:io ar os sp for on bs 代码 ad
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)
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;
}
};
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.
HappyLeetcode1 Reverse Words in a String
标签:io ar os sp for on bs 代码 ad
原文地址:http://www.cnblogs.com/chengxuyuanxiaowang/p/4161531.html