- 论坛徽章:
- 0
|
LZ的题目本来是判断有没有满足条件的字符
而不是求出那个字符。
大多数人都看错题了 呵呵
通常对于求出在一个列表中出现次数大于总数一半的元素问题。 是可以用一个与快速排序相类似的算法的。
具体到本题 有一个特点不知道大家注意到没有。
这个列表是字符串而元素是字符~~~~
如果这个字符是ASCII字符的话那么一切就都简单了。 因为ASCII总共才128个。
我们可以建立一个长度为128的数组, 用字符的ASCII作为下标, 数组中的元素是出现的次数。
- #include <stdio.h>
- int main(){
- int chr_count[128];
- int len;
- char str[] = "hellooooooo";
- char *p = str;
- memset(chr_count, 0, sizeof(chr_count));
- while(*p){
- chr_count[(int)*p]++;
- p++;
- }
- len = p - str;
- p = str;
- while(*p){
- if(chr_count[(int)*p] > (len + 1)/ 2){
- printf("%c\n", *p);
- return 0;
- }
- p++;
- }
- return 0;
- }
复制代码 |
|