Code War每天一练第三天
Posted zch-boke
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Code War每天一练第三天相关的知识,希望对你有一定的参考价值。
Take 2 strings s1
and s2
including only letters from a
to z
. Return a new sorted string, the longest possible, containing distinct letters,
- each taken only once - coming from s1 or s2.
- #Examples: ``` a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq"
- longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" ```
做题思路
1、将字符串 s1和s2 链接成一个新字符串
2、去掉重复字符,返回新一个新无重复字符串
3、将字符串排序
1 char * repeat(char *s) 2 { 3 //char *temp = s; 4 int i = 0, j, k; 5 int len = strlen(s); 6 7 for (i = 0; i < len; i++) 8 { 9 for ( j = i + 1; j < len; j++) 10 { 11 if (s[i] == s[j]) 12 { 13 for ( k = j; k < len; k++) 14 { 15 s[k] = s[k + 1]; 16 //printf("%c ", s[k]); 17 } 18 len--; 19 j--; //注:如果j--的话那么下一次循环j++就跳过一次比较 20 } 21 } 22 23 } 24 return s; 25 26 } 27 28 char* longest(char* s1, char* s2) { 29 // your code 30 //char *temp; 31 char *temp = (char *)malloc(strlen(s1)+strlen(s2)+1); 32 //strcat(s1, s2); //不能直接使用strcat否则可能产生写入冲突,需保证s1足够大 33 //将两字符串链接成一个字符串 34 strcpy(temp, s1); 35 strcat(temp, s2); 36 //strcat(s1, s2); 37 printf("%s ", s1); 38 temp = repeat(temp); 39 for (int i = 0; i < (int)strlen(temp); i++) 40 { 41 for (int j = i; j < (int)strlen(temp); j++) 42 { 43 if (temp[i] > temp[j]) 44 { 45 char tem = temp[i]; 46 temp[i] = temp[j]; 47 temp[j] = tem; 48 } 49 } 50 } 51 return temp; 52 53 }
这是一些大神的代码
1 char* longest(char* s1, char* s2) { 2 char letters [26] = {0}, *temp, *final = temp = (char *) calloc(sizeof(char), 26);; 3 while(*s1) letters[*(s1++) - ‘a‘]++; 4 while(*s2) letters[*(s2++) - ‘a‘]++; 5 6 for(int i = 0; i < 26; i++) 7 if(letters[i]) 8 *(temp++) = ‘a‘ + i; 9 10 return final; 11 }
以上是关于Code War每天一练第三天的主要内容,如果未能解决你的问题,请参考以下文章