以单词为单位反转字符串,要求不申请任何空间

来源:互联网 发布:叶问3游戏网络无连接 编辑:程序博客网 时间:2024/04/30 15:18

问题描述:

存在一个可读写的字符串,其中包括若干单词,单词间以空格区分,要求以单词为单位对字符串进行反转。

 

算法思想:

(1)利用异或运算可以不申请空间进行字符交换

(2)利用递归的思想

(3)使用strchr函数区分单词

 

解决方案:

include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include<iostream>
using namespace std;
 

void recursive_swap_char(char* lhs, char* rhs)// Using recursive to swap char.
{
 if(rhs <= lhs)
  return;

 *lhs ^= *rhs;
 *rhs ^= *lhs;
 *lhs ^= *rhs;
 
 recursive_swap_char(lhs + 1, rhs - 1);
}


void recursive_word_reverse(char* cur, char* next)// Using recursive to reverse chars of word
{
 // If this is the last word, reverse as a string
 if(next == NULL)
 {
  recursive_swap_char(cur, cur + strlen(cur) - 1);
  return;
 }

 // Reverse char within current word
 recursive_swap_char(cur, next - 1);

 // Reverse next word
 recursive_word_reverse(next + 1, strchr(next + 1, ' '));
}

char* reverse_by_word(char* src)
{
 // If only one word, return directly
 if(strchr(src, ' ') == NULL)
  return src;

 // Reverse whole string
 recursive_swap_char(src, src + strlen(src) - 1);

 // Reverse word
 recursive_word_reverse(src, strchr(src, ' '));

 return src;
}

void print(char* src)
{
 cout << "src:    " << src << endl;
 cout << "dest:   " << reverse_by_word(src) << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
 char one[] = "one";
 char one_two[] = "one two";
 char one_two_three[] = "one two three";
 char one_two_three_four[] = "one two three four";
 char str_for_test[] = "There is a program for test";
 
 print(one);
 print(one_two);
 print(one_two_three);
 print(one_two_three_four);
 print(str_for_test);

 getchar();
}

 

 

原创粉丝点击