逆序字符串

记得最开始学编程的时候逆序字符串都是先malloc一个空间,然后将原字符串反向拷贝过去,但在面试或者笔试的时候不会太这么随意,都会给一些限制。
要求不得另外申请内存,即原地逆序:

int reverse_str(char *str)
{
	char *str_tail_p = str;
	char *str_head_p = str;
	char tmp = 0;

	if (str == NULL) {
		return -1;
	}

	while (*str_tail_p) {
		str_tail_p++;
	}

	/*指向最后一个元素*/
	str_tail_p -= 1;

	while(str_tail_p > str_head_p) {
		/*使用了临时变量*/
		tmp = *str_head_p;
		*str_head_p++ = *str_tail_p;
		*str_tail_p-- = tmp;
	}

	return 0;
}

要求既不能另外申请内存也不能使用临时变量,那就只能依赖于异或了:

int reverse_str(char *str)
{
	char *str_tail_p = str;
	char *str_head_p = str;

	if (str == NULL) {
		return -1;
	}

	while (*str_tail_p) {
		str_tail_p++;
	}

	/*指向最后一个元素*/
	str_tail_p -= 1;

	while(str_tail_p > str_head_p) {
		/*使用异或运算*/
		*str_head_p = *str_head_p ^ *str_tail_p;
		*str_tail_p = *str_head_p ^ *str_tail_p;
		*str_head_p = *str_head_p++ ^ *str_tail_p--;
	}

	return 0;
}

来个网上经常看到的题,以单词为单位对句子就行逆序,比如:
input:Say hello to the fucking world
output:world fucking the to hello Say
解题思路:
step1 先将每个单词进行逆序,yaS olleh ot eht gnikcuf dlrow
step2 将整个字符串整体逆序,world fucking the to hello Say

/*用始末指针标识单词范围*/
void reverse_word(char *str_head, char *str_tail)
{
	char *str_head_p = str_head;
	char *str_tail_p = str_tail;

	while(str_tail_p > str_head_p) {
		*str_head_p = *str_head_p ^ *str_tail_p;
		*str_tail_p = *str_head_p ^ *str_tail_p;
		*str_head_p = *str_head_p++ ^ *str_tail_p--;		
	}
}

int reverse_sentence(char *sentence)
{
	char *sentence_p = sentence;
	char *word_head_p = NULL;
	char *word_tail_p = NULL;

	if (sentence == NULL) {
		return -1;
	}

	/*找到第一个非空格字符*/
	while (*sentence_p) {
		if (*sentence_p == ' ') {
			sentence_p++;
			continue;
		}

		word_head_p = sentence_p;
		break;
	}

	/*全是空格*/
	if (!word_head_p) {
		return 0;
	}

	while (*sentence_p) {
		if (*sentence_p == ' ') {
			word_tail_p = sentence_p - 1;
			/*出现空格且空格前有单词*/
			reverse_word(word_head_p, word_tail_p);
			word_head_p = sentence_p + 1;
		}

		sentence_p++;
	}

	/*找到最后一个字符*/
	sentence_p -= 1;
	/*当原句为Say hello to the fucking world'\0',即句子不是以空格结尾,
	**此时时最后一个单词还没有逆序*/
	if (*sentence_p != ' ') {
		word_tail_p = sentence_p;
		reverse_word(word_head_p, word_tail_p);
	}

	/*整个句子逆序*/
	reverse_word(sentence, sentence_p);

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值