[CareerCup] Arrays and Strings―Q1.2

2014-11-24 10:47:43 · 作者: · 浏览: 0

题目:

Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)

翻译:

编写代码,实现翻转一个C风格的字符串的功能。(C风格的意思是abcd需要用5个字符来表示,最后一个字符为空字符'')

思路:

最简单的方法当然是取得字符串的长度,而后一个for循环,交换左右两边对应位置上的字符。但这里题目既然强调了C语言风格的字符串,我们最好在代码中利用到字符串末尾的'',这样我们可以设置两个指针pLeft和pRight,pLeft指向首符,pRight指向最后一个有效字符(即''前面的字符),向中间依次移动两指针,只要pLeft小于pRight,就交换二者指向的字符。由于要将pRight先移动到最后,因此时间复杂度为O(n)。

实现代码:

/****************************************************************
题目描述:
编写代码,实现翻转一个C风格的字符串的功能。
C风格的意思是abcd需要用5个字符来表示,最后一个字符为空字符''。
Date:2014-03-15
*****************************************************************/
#include
  
   
/*
交换两字符
*/
void swap(char *a,char *b)
{
	*a = *a + *b;
	*b = *a - *b;
	*a = *a - *b;
}

/*
反转字符串
*/
void reverse(char *str)
{
	if(!str)
		return;
	char *pLeft = str;
	char *pRight = str;
	while(*pRight != '')
		pRight++;
	pRight--;
	while(pLeft < pRight)
		swap(pLeft++,pRight--);
}

int main()
{
	//注意这里不能定义为 char *str = thanks,
	//这样定义的是字符串常量,不可修改。
	char str[] = thanks;
	reverse(str);
	puts(str);
	return 0;
}

  

测试结果:

/