小练习- 1

题目:将字符数组a转换成apple an is this,可以把它叫做字符数组单词逆序
要求:1、不能开辟新的数组或者其他内存单元,使其空间复杂度为O(1)
         {空间复杂度:空间复杂度是对一个算法在运行过程中临时占用存储空间大小的量度
         如当一个算法的空间复杂度为一个常量,即不随被处理数据量n的大小而改变时,可表示为O(1)
         表示该程序所占用的空间和所用数据量无关}

        2、不能使用C++特性

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char str[] = "this is an apple";
  int str_len = sizeof(str);
  
  cout << "Length of string is " << str_len << endl;

// 翻转字符串
  for (int i = 0; i < str_len/2 ; i++)
  {
    str[str_len - 1] = str[i];
    str[i] = str[str_len -2 -i];
    str[str_len - 2 - i] = str[str_len - 1];
  }

  str[str_len - 1] = '\0';
  
  cout << str << endl;
   
 
 //纠正字母  
  int word_len = 0;

  for (int i = 0; i < str_len; i++)
  {
    word_len++;
    if (str[i] == '\0' || str[i] == ' ')
    {
      for (int j = 0; j < word_len / 2; j++)
      {
        str[i] = str[i - word_len + 1 + j];
        str[i - word_len + 1 + j] = str[i - 1 - j];
        str[i - 1 - j] = str[i];
      }
      str[i] = ' ';
      word_len = 0;
    }
  }
  
  str[str_len - 1] = '\0';

  cout << str << endl;
  return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值