leetcode string reverse word order column

THE

problem

Insert picture description here

solution

Code



//不知不觉刷到42题了,这道题主要思想就是先翻转所有字符,再逐个单词翻转,逐个单词翻转的时候考虑三种不同情况即可。
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

  1. 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.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114191182