该算法实现的核心是转置,abcde——>edcba,下面是数组的转置方法
void flip(char[] cs)
{
int len=cs.Length-1;
for (int t = 0; t < cs.Length / 2;t++,len-- )
{
char temp = cs[t];
cs[t] = cs[len ];
cs[len] = temp;
}
}
字符串abcde,m=3为转置位数,具体实现如下:
static void Main(string[] args)
{
string str = "abcde";
String result=new Program().process(str, 3);
Console.WriteLine(result);
Console.ReadLine();
}
private String process(String str,int m){
char[] cs=str.ToArray();
flipHand(cs,0,m-1);
flipHand(cs,m,cs.Length-1);
flipHand(cs,0,cs.Length-1);
reflip new String(cs);
}
private void flipHand(char[] cs, int i, int j)
{
int length = j - i + 1;
for (int t = 0; t < length / 2; t++, i++)
{
char temp = cs[i];
cs[i] = cs[j - t];
cs[j - t] = temp;
}
}
输出结果:deabc