字符串旋转问题 求助。
最近看编程珠玑碰到字符串旋转问题
一个思路是
ab 变成 ba
步骤:
1. a1a2b (a1长度等于b)
2. ba2a1
3 递归地将a2a1换位置
于是我想上机实现。。。。冥思苦相 也没写出来递归的程序。。
完全没有任何思路。。
然后找到这个非递归代码:
void gcdrot(int rotdist, int n){ int i, j, p; if (rotdist == 0 || rotdist == n) return; i = p = rotdist; j = n - p; while (i != j) { /* invariant: x[0 ..p-i ] is in final position x[p-i..p-1 ] = a (to be swapped with b) x[p ..p+j-1] = b (to be swapped with a) x[p+j..n-1 ] in final position */ if (i > j) { swap(p-i, p, j); i -= j; } else { swap(p-i, p+j-i, i); j -= i; } } swap(p-i, p, i);}
#include "stdio.h"char *swap_string(char *a,int n,int k){ int m = n/2; if(k < m) { char tmp; tmp=a[k]; a[k] = a[n-k-1]; a[n-k-1] = tmp; k++; swap_string(a,n,k); } return a;}int main(){ char p[] = "abcdefghijkl"; int n = sizeof(p)/sizeof(char); char *s; int k = 0; s = swap_string(p,n-1,k); printf("%s\n",s); return 0;}