typedef struct st{ int pst; int* arr; }st; #define min(a,b) (a)<(b)?(a):(b) int findRotateSteps(char * ring, char * key){ int i,j,k,minStep=100000,val; int keylen=strlen(key), ringlen=strlen(ring); st ans[128]={0}; int* step=(int*)calloc(ringlen,sizeof(int)); for (i=0; i<ringlen; i++) { if (strchr(key,ring[i])) { if (ans[ring[i]].pst == 0) ans[ring[i]].arr=(int*)calloc(ringlen,sizeof(int)); ans[ring[i]].arr[(ans[ring[i]].pst)++]=i; } } for (i=keylen-2; i>=0; i--) { int* temp=(int*)calloc(ans[key[i]].pst,sizeof(int)); memset(temp,0x7f, ans[key[i]].pst*sizeof(int)); for (j=0; j<ans[key[i]].pst; j++) { for (k=0; k<ans[key[i+1]].pst; k++) { val=min(abs(ans[key[i+1]].arr[k] - ans[key[i]].arr[j]),ringlen-abs(ans[key[i+1]].arr[k] - ans[key[i]].arr[j])); if (val+step[k] < temp[j]) temp[j]=val+step[k]; } } step=temp; } for (k=0; k<ans[key[0]].pst; k++) { val=min(ans[key[0]].arr[k],ringlen-ans[key[0]].arr[k]); if (val+step[k] < minStep) minStep=val+step[k]; } return minStep+keylen; }