暂时无法访问博客堂,先贴到这里了,等能访问了再复制过去……
其实这问题源于轻剑傲风解答尉迟方兄遇到的面试题那个帖子。这道题如下:
1、reverse a sentence in place. 例子:I am yuchifang -> yuchifang am I 注意in place |
下面是我用轻剑傲风的思路重新写了一遍,但没有用任何字符串函数,整个过程完全“就地”解决,没有将一个字符写到原数组的存储空间之外。代码中有将System.String转换成Char[]的代码,这个不应该算我算法中的一部分。此外我还用了String.Length,不得不用一下,虽然解法最好不包含任何.NET的内置函数……
语言是:C++/CLI
// ReverseInPlace.cpp: 主项目文件。
#include "stdafx.h"
using namespace System;
template <typename T>
void SwapInPlace(interior_ptr<T> a, interior_ptr<T> b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main(array<System::String ^> ^args)
{
if (args->Length > 0)
{
String^ s = args[0];
int length = s->Length; //risk: CLR property
if (length < 1)
{
return 0;
}
//Step one, reverse the string in place.
array<Char>^ chararr = s->ToCharArray();
for (int i = 0; i < (length - 1) / 2.0; i++)
{
SwapInPlace<Char>(&chararr[i], &chararr[length - 1 - i]);
}
//Step two, reverse every word in place.
int lastSpace = 0;
for (int j = 0; j <= length; j++)
{
if (j == length || chararr[j] == ' ')
{
for (int k = lastSpace; k < lastSpace + (j - 1 - lastSpace ) / 2.0; k++)
{
SwapInPlace<Char>(&chararr[k], &chararr[j - 1 - k + lastSpace]);
}
lastSpace = j + 1;
}
}
Console::WriteLine(chararr);
}
return 0;
}
#include "stdafx.h"
using namespace System;
template <typename T>
void SwapInPlace(interior_ptr<T> a, interior_ptr<T> b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main(array<System::String ^> ^args)
{
if (args->Length > 0)
{
String^ s = args[0];
int length = s->Length; //risk: CLR property
if (length < 1)
{
return 0;
}
//Step one, reverse the string in place.
array<Char>^ chararr = s->ToCharArray();
for (int i = 0; i < (length - 1) / 2.0; i++)
{
SwapInPlace<Char>(&chararr[i], &chararr[length - 1 - i]);
}
//Step two, reverse every word in place.
int lastSpace = 0;
for (int j = 0; j <= length; j++)
{
if (j == length || chararr[j] == ' ')
{
for (int k = lastSpace; k < lastSpace + (j - 1 - lastSpace ) / 2.0; k++)
{
SwapInPlace<Char>(&chararr[k], &chararr[j - 1 - k + lastSpace]);
}
lastSpace = j + 1;
}
}
Console::WriteLine(chararr);
}
return 0;
}