THE
problem
solution
Code
class Solution {
public:
void Reverse(string& sent, int begin, int end)
{
if (begin<0 || end<0)
return;
while (begin<end)
{
char c;
c = sent[begin];
sent[begin] = sent[end];
sent[end] = c;
begin++;
end--;
}
}
string ReverseSentence( string &str) {
int length = str.size();
if (length <= 1)
return str;
int pBegin = 0;
int pEnd = 0;
while (str[pEnd] != '\0')
{
pEnd++;
}
pEnd--;
Reverse(str, pBegin, pEnd);
pBegin = pEnd = 0;
while (str[pBegin] != '\0')
{
if (str[pBegin] == ' ')
{
pBegin++;
pEnd++;
}
else if (str[pEnd] == ' ' || str[pEnd] == '\0')
{
Reverse(str, pBegin, --pEnd);
pBegin = ++pEnd;
}
else
{
pEnd++;
}
}
return str;
}
};
Summary and reflection
- This hard topic has too many details. It belongs to the most difficult problem in the simple string problem. No ac comes out. Copy the answer.