贪心法 合并字符串的C语言代码
时间: 2023-12-24 08:50:06 浏览: 32
以下是合并字符串的C语言代码(使用贪心法):
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n;
scanf("%d", &n);
char** strs = (char**) malloc(n * sizeof(char*));
for (int i = 0; i < n; i++) {
strs[i] = (char*) malloc(100 * sizeof(char));
scanf("%s", strs[i]);
}
char* res = (char*) malloc(100 * n * sizeof(char));
int len = 0;
while (true) {
int max = -1;
int idx = -1;
for (int i = 0; i < n; i++) {
if (strs[i] == NULL) {
continue;
}
int l = strlen(strs[i]);
if (l > max) {
max = l;
idx = i;
}
}
if (idx == -1) {
break;
}
strcat(res + len, strs[idx]);
len += strlen(strs[idx]);
strs[idx] = NULL;
}
printf("%s\n", res);
for (int i = 0; i < n; i++) {
free(strs[i]);
}
free(strs);
free(res);
return 0;
}
```
希望能够满足您的需求,如果您还有其他问题,也欢迎随时向我提问哦!😊