关闭

[Leetcode]字符串的反转

141人阅读 评论(0) 收藏 举报
分类:

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

Example:

Given s = "hello", return "olleh".

很简单,针对长度为奇偶情况不同,作对应的处理:

char* reverseString(char* rs) 
{
    char *p = NULL, *q = NULL, *mid = NULL;
	char tmp = '\0';
	int i, len;
	len = strlen(rs);
	
	printf("len=%d\n", len);
	char *s = malloc(len + 1);
	memset(s, 0, len+1);
	strncpy(s, rs, len);
	
	if (len <= 1)
		return rs;
		
	if (len % 2 == 0)
	{
		for(i = 0; i < len / 2; i ++)
		{
			tmp = s[i];
			s[i] = s[len - i - 1];
			s[len - i - 1] = tmp;
		}	
	}
	else
	{
		p = &s[0];
		mid = &s[(len / 2) + 1];//middle elem
		q = &s[len - 1];
		
		while(p != mid)
		{
			tmp = *p;
			*p = *q;
			*q = tmp;
			
			p ++;
			q --;
		}
	}
	
	return s;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:138605次
    • 积分:2734
    • 等级:
    • 排名:第13199名
    • 原创:140篇
    • 转载:19篇
    • 译文:2篇
    • 评论:15条
    文章分类