文章

9

粉丝

0

获赞

45

访问

6.2k

头像
前缀字符串 题解:C
P1098 中山大学机试题
发布于 2026年3月
阅读数 892

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp (const void *a, const void *b) {
	char *x = *(char **)a;
	char *y = *(char **)b;
	return (strlen(x) > strlen(y)) - (strlen(x) < strlen(y));
}

int is_pre (char *str1, char *str2) {
	int res = strncmp(str1, str2, strlen(str1));
	return res == 0 ? 1 : 0;
}

int main () {
	int n;
	while (scanf("%d", &n) == 1) {
		if (n == 0) continue;
		char **str = (char **)malloc(sizeof(char *) * n);
		for (int i = 0; i < n; i++) {
			str[i] = (char *)malloc(sizeof(char) * 21);
			scanf("%s", str[i]);
		}
		
		qsort(str, n, sizeof(char *), cmp);
		int cnt = 0;
		for (int i = 0; i < n - 1; i++) {
			int flag = 1;
			for (int j = i + 1; j < n; j++) {
				if (is_pre(str[i], str[j])) flag = 0;	
			}
			if (flag == 1) cnt++; 
		}
		cnt++;
		printf("%d\n", cnt);
 	}
	
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发