文章
454
粉丝
0
获赞
1
访问
10.6k
给出一个长度不超过 100 的 01 串,输出所有出现次数大于 1 的子串及其出现次数,按字典序排序。多组。
枚举所有起点与长度,把所有子串(含重复)收集到数组里。
整体按字典序排序,相同的子串会聚在一起,顺次统计每段的长度即为出现次数。
只输出次数大于 1 的子串。先排序再统计,避免两两比对带来的三次方复杂度。
O(L² log L),L ≤ 100。
C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char store[5100][105];
static char *arr[5100];
static int cmp(const void *a, const void *b) {
return strcmp(*(char *const *)a, *(char *const *)b);
}
int main(void) {
char buf[105];
while (scanf("%104s", buf) == 1) {
int n = (int)strlen(buf), i, len, m = 0;
for (i = 0; i < n; i++) {
for (len = 1; i + len <= n; len++) {
memcpy(store[m], buf + i, len);
store[m][len] = 0;
arr[m] = store[m];
m++;
}
}
qsort(arr, (size_t)m, sizeof(char *), cmp);
i = 0;
while (i < m) {
int j = i + 1;
while (j < m && str...
登录后发布评论
暂无评论,来抢沙发