编程练习——字符串反转

字符串反转

  • 时间限制:1秒
  • 空间限制:32768K

描述

写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。

  • 输入 N 个字符
  • 输出该字符串反转后的字符串
  • 示例:输入 abcd,输出 dcba

C 代码实现

#include <stdio.h>
#include <string.h>

int main(void)
{
	char str[128];
	char tmp;

	scanf("%s", str);

	int i = 0;
	int j = strlen(str) - 1;

	while(j > i) {
	
		tmp = str[i];
		str[i] = str[j];
		str[j] = tmp;

		i++;
		j--;
	}

	printf("%s\n", str);

	return 0;
}

如果不想使用中间变量交换,可以做加减运算,如下:

	while(j > i) {
	
		str[i] = str[i] + str[j];
		str[j] = str[i] - str[j];
		str[i] = str[i] - str[j];

		i++;
		j--;
	}

Python 代码实现

str1 = input()
str1 = str1[::-1]
print(str1)

执行效率

输入:abcdefghijklmnopqrstuvwxyz

  • Python 代码:运行时间:31ms,内存占用:4m
  • C 代码:运行时间:2ms,内存占用:220k
发布了299 篇原创文章 · 获赞 1219 · 访问量 159万+

猜你喜欢

转载自blog.csdn.net/luckydarcy/article/details/102598944