int len = strlen(s); char* out_string = (char*)malloc(sizeof(char) * (len + 1)); char* out_idx = out_string;
char* right = s + len - 1; char* left = right; //处理单字符 if (right == s) { memcpy((void*)out_idx, (void*)left, sizeof(char) * (right - left + 1)); out_idx += right - left + 1; *out_idx = '\0'; return out_string; } //处理多字符 while (right > s) { while (*right == ' ' && right > s) right--; if (*right == ' ') break; left = right; while (*left != ' ' && left > s) left--; (left != s || (left == s && *left == ' ')) ? left += 1 : 0; //判断是否为首字符,防止越界 memcpy((void*)out_idx, (void*)left, sizeof(char) * (right - left + 1)); out_idx += right - left + 1; *(out_idx++) = ' '; right = left - 1; } *(out_idx - 1) = '\0';//字符串结束符 return out_string; }
此方案指针是从后向前移动,需要注意数组越界/指针越界。其中leetcode会报错,本地VS可运行成功。
> runtime error: store to address 0x502000000040 with insufficient
space for an object of type ‘char’