C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
//【题目】华为2013校园招聘机试题目题4:删除一个字符串中出现次数最少的字符
// 函数原型为:char * delChar(char *s,int iLen) //【输入】s为输入字符串,iLen为输入字符串长度 // 如输入字符串为“abcdd”,输出为"dd" // 字符串中只有小写字母,不含空格且字符串最大长度不超过20 #include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 20 //查找字符S是否在字符数组中 int WetherInVisit(char s, char* visit) { int i = 0; while(visit[i] != '\0') { if(s == visit[i]) { return i; } else { i++; } } return -1; } //查看数字i是否为数组中最小的数 int WetherIsMin(unsigned int i, unsigned int* array, unsigned int len) { unsigned int temp; for(temp = 0; temp < len; temp++) { if(i > array[temp]) return 1; else return 0; } } //删除字符串中出现次数最少的字符 char* declar(char *s,int len) { unsigned int count[MAX]; char visit [MAX]; char*Renew = (char*)malloc(len + 1); int len_visit = 0; int position, i, j = 0; visit[0] = '\0'; for(i = 0 ; i < len; i++) { position = WetherInVisit(s[i], visit); if(position == -1) { visit[len_visit] = s[i]; count[len_visit] = 1; len_visit++; visit[len_visit] = '\0'; } else { count[position]++; } } for(i = 0; i < len; i++) { position = WetherInVisit(s[i], visit); if(WetherIsMin(count[position], count, len_visit) == 1) { Renew[j] = s[i]; j++; } } Renew[j] = '\0'; return Renew; } void main() { int i = 0; int len = 0; //输入字符串的长度 char s[MAX]; char *New; printf("请输入一组字符串,最长为20个字符\n"); while(gets(s) != NULL) { for(i = 0; s[i] != '\0'; i++) { len++; } New = declar(s, len); printf("删除后的字符串为\n"); printf("%s\n", New); free(New); printf("\n请输入下一组字符串,最长为20个字符,输入其他字符退出\n"); } } |