所谓逆转字符串,就是将一个字符串头尾倒置,变成一个新的字符串
如:abcde -> edcba
cccaa -> aaccc
逆转字符串可以在线性时间内完成,所需时间与字符串长度成正比。逆转的方法很简单,只需要遍历一半字符串,并将对应位置上的字符对换即可。字符串中的字符对应一个正整数,因此下面的三种方法都是利用了变换两个整型变量的思想。
1、利用最简单的交换两个变量的值的方法,即 t = a, a = b, b = t这样的方式
char* Reverse(char* str, int length)
{
for (int i = 0; i < length / 2; ++i)
{
str[length] = str[i];
str[i] = str[length - 1 - i];
str[length - 1 - i] = str[length];
}
str[length] = 0;
return str;
}
2、利用一种巧妙的数字技巧来交换两个变量的值,即 a = a + b, b = a - b, a = a - b
char* Reverse(char* str, int length)
{
for (int i = 0; i < length / 2; ++i)
{
str[i] = str[i] + str[length - 1 - i];
str[length - 1 - i] = str[i] - str[length - 1 - i];
str[i] = str[i] - str[length - 1 - i];
}
return str;
}
3、利用位运算来交换两个变量的值,即 a = a ^ b, b = a ^ b, a = a ^ b
char* Reverse(char* str, int length)
{
for (int i = 0; i < length / 2; ++i)
{
str[i] = str[i] ^ str[length - 1 - i];
str[length - 1 - i] = str[i] ^ str[length - 1 - i];
str[i] = str[i] ^ str[length - 1 - i];
}
return str;
}