int* shortestToChar(char * S, char C, int* returnSize){ int strLength = strlen(S);//字符串长度 int *arr=(int*)malloc(sizeof(int)*strLength); int prev = -strLength; int i; for(i=0;i<strLength;i++){ if(S[i] == C) prev = i; arr[i] = i-prev; } for(i = prev-1;i>=0;i--){ if(S[i] == C) prev = i; if(arr[i] > prev-i) arr[i] = prev-i; } *returnSize = strLength; return arr; }
int MinVal(int i,int* Cpst,int pst) { int min = abs(Cpst[0] - i); for (int j=1; j<pst; j++) { if (abs(Cpst[j] - i) < min) min = abs(Cpst[j] - i); if (!min) return 0; } return min; } int* shortestToChar(char * S, char C, int* returnSize){ int* Cpst = (int*)calloc(strlen(S),sizeof(int)); int* arr = (int*)calloc(strlen(S),sizeof(int)); int pst = 0; int i; for (i=0; i<strlen(S); i++) { if (S[i] == C) Cpst[pst++] = i; } for (i=0; i<strlen(S); i++) { arr[i] = MinVal(i,Cpst,pst); } *returnSize = strlen(S); return arr; }