LeetCode 344: Reverse String 题解

来源:互联网 发布:linux 开机自启动脚本 编辑:程序博客网 时间:2024/05/19 04:50

从今天开始我也来刷刷 LeetCode,从最简单的题开始。


LeetCode 344: Reverse String

Problem:
Write a function that takes a string as input and returns the string reversed.


Example:
Given s = “hello”, return “olleh”.


这道题很简单,就是翻转字符串。LeetCode的题目答案都是以函数作为框架的,所以我们需要按照要求讲程序写到给定的函数中,并且返回正确的答案。

这道题可以从字符串的开头和结尾开始交换,然后逐渐向字符串的中间靠近,直到全部交换完成,整个字符串就翻转了,另外,这种方法不需要关心字符串的长度是奇数还是偶数。

复习到的知识点:C语言中的指针是可以进行加减运算的,字符串在内存中是连续存储的,并且以空字符(’\0’)结尾

通过代码如下:

char* reverseString(char* s) {    char* low = s;                  //字符串的第一个字符    char* high = s + strlen(s) - 1; //字符串的最后一个字符    char temp;    while(low < high){ //从两边到中间逐次交换字符        temp = *low;        *low++ = *high;        *high-- = temp;    }    return s;}
0 0
原创粉丝点击