标签:void 原来 sub 递归 while 跳过 题目 空格 tle
class Solution {
public:
//void swap()
void Reversesub(string &str,int a,int b){
while(a<b)
swap(str[a++],str[b++]);
}
string ReverseSentence(string str) {
int n=str.size();
Reversesub(str,0,n);
int i=0;
int a=0,b=0;
while(i<n) {
while(i<n && str[i]==‘ ‘)
i++;
a=b=i;
while(i<n && str[i]!=‘ ‘) {
i++;
b++;
}
Reversesub(str,a,b-1);
}
return str;
}
};
class Solution {
public:
//void swap()
void Reversesub(string &str,int a,int b){
while(a<b)
swap(str[a++],str[b--]);
}
string ReverseSentence(string str) {
int n=str.size();
Reversesub(str,0,n-1);
int i=0;
int a=0,b=0;
while(i<n) {
while(i<n && str[i]==‘ ‘)
i++;
a=b=i;
while(i<n && str[i]!=‘ ‘) {
i++;
b++;
}
Reversesub(str,a,b-1);
}
return str;
}
};
class Solution {
public:
void ReverseWord(string &str, int s, int e)
{
while(s < e)
swap(str[s++], str[e--]);
}
string ReverseSentence(string str) {
ReverseWord(str, 0, str.size() - 1); //先整体翻转
int s = 0, e = 0;
int i = 0;
while(i < str.size())
{
while(i < str.size() && str[i] == ‘ ‘) //空格跳过
i++;
e = s = i; //记录单词的第一个字符的位置
while(i < str.size() && str[i] != ‘ ‘) //不是空格 找单词最后一个字符的位置
{
i++;
e++;
}
ReverseWord(str, s, e - 1); //局部翻转
}
return str;
}
};
标签:void 原来 sub 递归 while 跳过 题目 空格 tle
原文地址:http://www.cnblogs.com/dd2hm/p/7417581.html