题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <stdio.h> #include <string.h> #define MAX_LENGTH 10 #define MAX_WORDS 1000 // 检查两个单词是否是兄弟单词 int areBrotherWords(char word1[], char word2[]) { // 如果两个单词长度不同,则它们不可能是兄弟单词 if (strlen(word1) != strlen(word2)) return 0; // 统计两个单词中每个字母出现的次数 int count1[26] = {0}; int count2[26] = {0}; for (int i = 0; i < strlen(word1); i++) { count1[word1[i] - 'a']++; count2[word2[i] - 'a']++; } // 检查每个字母出现的次数是否相同 for (int i = 0; i < 26; i++) { if (count1[i] != count2[i]) return 0; } return 1; } // 根据字典和给定的单词找到兄弟单词的个数 int findBrotherWordsCount(char dictionary[][MAX_LENGTH], int n, char x[]) { int count = 0; for (int i = 0; i < n; i++) { if (strcmp(dictionary[i], x) != 0 && areBrotherWords(dictionary[i], x)) count++; } return count; } // 根据字典和给定的单词找到字典序排列后的第k个兄弟单词 void findKthBrotherWord(char dictionary[][MAX_LENGTH], int n, char x[], int k) { char brotherWords[MAX_WORDS][MAX_LENGTH]; int count = 0; // 找到所有兄弟单词 for (int i = 0; i < n; i++) { if (strcmp(dictionary[i], x) != 0 && areBrotherWords(dictionary[i], x)) { strcpy(brotherWords[count], dictionary[i]); count++; } } // 按字典序排序兄弟单词 for (int i = 0; i < count - 1; i++) { for (int j = i + 1; j < count; j++) { if (strcmp(brotherWords[i], brotherWords[j]) > 0) { char temp[MAX_LENGTH]; strcpy(temp, brotherWords[i]); strcpy(brotherWords[i], brotherWords[j]); strcpy(brotherWords[j], temp); } } } // 输出第k个兄弟单词 if (k <= count) printf("%s\n", brotherWords[k - 1]); } int main() { int n; scanf("%d", &n); char dictionary[MAX_WORDS][MAX_LENGTH]; for (int i = 0; i < n; i++) scanf("%s", dictionary[i]); char x[MAX_LENGTH]; scanf("%s", x); int k; scanf("%d", &k); int brotherWordsCount = findBrotherWordsCount(dictionary, n, x); printf("%d\n", brotherWordsCount); findKthBrotherWord(dictionary, n, x, k); return 0; }
排行榜第20. //用C写程序真的强。