标签:不能 span shell shel main nbsp i++ 取字符串 排序
1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 5 int Cmp(const void* a, const void* b) 6 { 7 char* s1 = *(char**)a; 8 char* s2 = *(char**)b; 9 10 return strcmp(s1, s2); 11 } 12 13 int minimumLengthEncoding(char** words, int wordsSize) 14 { 15 if (words == NULL || wordsSize == 0) 16 { 17 return 0; 18 } 19 int i, j,res = 0; 20 int totalLen = 0; 21 int* size = (int*)calloc(wordsSize, sizeof(int)); 22 char t[9] = { 0 }; 23 24 for (i = 0; i < wordsSize; i++) //每个字符串逆序 25 { 26 int len = strlen(words[i]); 27 for (j = 0; j < len / 2; j++) 28 { 29 char t = words[i][j]; 30 words[i][j] = words[i][len-j-1]; 31 words[i][len-j-1] = t; 32 } 33 } 34 qsort(words, wordsSize, sizeof(char*), Cmp); //字符串字典序排序 35 /*for (i = 0; i < wordsSize-1; i++) //冒泡排序 36 { 37 for (j = 0; j < wordsSize - 1 - i; j++) 38 { 39 if (strcmp(words[j], words[j + 1]) > 0) 40 { 41 strcpy(t, words[j]); 42 strcpy(words[j], words[j + 1]); 43 strcpy(words[j + 1], t); 44 } 45 } 46 }*/ 47 48 for (i = 0; i < wordsSize; i++) //总长度,并记录每个串个长度 49 { 50 size[i] = strlen(words[i]); 51 totalLen += size[i]; 52 } 53 totalLen += wordsSize; //加所有的‘#‘ 54 55 for (i = 0; i < wordsSize - 1; i++) 56 { 57 if (strncmp(words[i], words[i + 1], size[i]) == 0) 58 { 59 totalLen -= (size[i] + 1); 60 } 61 } 62 free(size); 63 return totalLen; 64 } 65 66 int main(void) 67 { 68 char** s; 69 int num; 70 s = (char **)malloc(sizeof(char*) * 6); 71 for (int i = 0; i < 6; i++) 72 { 73 s[i] = (char *)malloc(sizeof(char) * 10); 74 } 75 strcpy(s[0], "time"); 76 strcpy(s[1], "lime"); 77 strcpy(s[2], "hell"); 78 strcpy(s[3], "sometime"); 79 strcpy(s[4], "shell"); 80 strcpy(s[5], "me"); 81 82 num = minimumLengthEncoding(s, 6); 83 printf("%d", num); 84 return 0; 85 }
(Good topic)单词的压缩编码(leetcode3.28每日打卡)
标签:不能 span shell shel main nbsp i++ 取字符串 排序
原文地址:https://www.cnblogs.com/ZhengLijie/p/12586590.html