1. char* reverse_word(const char* str)
  2. {
  3.      int len = strlen(str);
  4.      char* restr = new char[len+1];
  5.      strcpy(restr,str);
  6.      int i,j;
  7.      for(i=0,j=len-1;i<j;i++,j--)
  8.      {
  9.           char temp=restr[i];
  10.           restr[i]=restr[j];
  11.           restr[j]=temp;
  12.      }
  13.      int k=0;
  14.      while(k<len)
  15.      {
  16.           i=j=k;
  17.           while(restr[j]!=' ' && restr[j]!='' )
  18.                j++;

  19.           k=j+1;
  20.           j--;
  21.           for(;i<j;i++,j--)
  22.           {
  23.                char temp=restr[i];
  24.                restr[i]=restr[j];
  25.                restr[j]=temp;
  26.           }
  27.      }
  28.      return restr;
  29. }
复制代码

如果考虑空间和时间的优化的话,当然可以将上面代码里两个字符串交换部分改为异或实现。
例如将
          char temp=restr;

          restr=restr[j];

          restr[j]=temp;

改为
          restr^=restr[j];

          restr[j]^=restr;

          restr^=restr[j];

 

 

 

        //"I am a student” => "student a am I"(只适合中间只有一个空格的情况,中间有多个空格的情况后续补上)
        static void ReverseWords(char[] sentence)
        {
            //先将整个句子反转,例如:“I am a student” => "tneduts a ma I"
            ReverseString(sentence, 0, sentence.Length-1);
            int startIndex = 0, endIndex = 0;
            int i = 0;
            while( i < sentence.Length)
            {
                if (sentence[i] == ' ')//Means the end of a word
                {
                    endIndex = i - 1;
                    ReverseString(sentence, startIndex, endIndex);
                    if (i + 1 < sentence.Length)
                    {
                        startIndex = i + 1;
                        endIndex = startIndex;
                    }
                }
                else
                {
                    endIndex++;
                }
                i++;

            }
           
        }

        //反转整个句子
        static void ReverseString(char[] str, int startIndex, int endIndex)
        {  
            int len = endIndex - startIndex + 1;
            char temp;
            for (int i = 0; i < len/2; i++)
            {
               
                temp = str[i + startIndex];
                str[i + startIndex] = str[startIndex + len - i - 1];
                str[startIndex + len - i - 1] = temp;
            }
        }

 

相关文章:

  • 2022-12-23
  • 2021-07-25
  • 2021-12-05
  • 2021-12-18
  • 2021-11-21
  • 2021-07-10
猜你喜欢
  • 2022-02-21
  • 2022-12-23
  • 2021-05-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-21
相关资源
相似解决方案