算法:统计字符出现的次数(仅限字母)

2018-09-04  本文已影响256人  Timemit
  1. 编程题:RLE算法,编写一个函数,实现统计字符次数的功能:例如输入为aaabbccc,输出为a3b2c3。不限语言。

这是一道算法题
1.首先我们得分析输入字符的肯能性
1).输入aaabbccc ,输出 a3b2c3,重复的字符在一起,这种是最简单的
2).输入AAaaabbBBcccC ,输出 A2B2C1a3b2c3,大小写字母放在一起,和第一种类似
3).输入abaaccbc ,输出 a3b2c3,重复的字符没在一块,我们需要逐一找到重复的字符,相对比较麻烦些。
4).输入abaAaBBcCcCCbc ,输出 A1B2C3a3b2c3,与第三种类似
目前大体上就是这四种输入的可能性。
2.根据输入的字符串找到规律
通过输入的字符串,我们可以确定只有字母(大小写),所以我们所要统计的字符种类就只有52种,在ASCII码表中"A" 的十进制是 65,"a" 的十进制是97,因此通过对应关系我们可以定义一个容量大小为58(为什么是58而不是52,这是因为a和A之前差了32,尽管中间有6个字符没用,但是为了方便处理,所以多定义6个字符的空间)的数组分别存每个字符出现的次数,这样就可以解决这个问题了。
3.根据2的规律编写c程序
代码如下

void c_sumOfCharacters(char * str){
     int i = 0;
     int num[58] = {0};
     while (str[i] != '\0') {
          if ('A' <= str[i] && str[i] <= 'Z') {
               int index = str[i] - 'A';
               num[index] = num[index]+1;
          }else if ('a' <= str[i] && str[i] <= 'z'){
               int index = str[i] - 'a' + 32;
               num[index] = num[index]+1;
          }
          i++;
     }
     for (int i = 0; i < 58; i++) {
          int count = num[i];
          if (count != 0) {
               char c = 'A'+i;
               printf("%c%d",c,count);
          }
     }
}

输入:AbbFFeeewwQQQAFF
输出:A2F4Q3b2e3w2
4.oc代码
oc的实现逻辑相比较c语言有比较大的差别,没有运用2中所描述的规律,不过用了oc中字典的特性,不可重复的特性,我是用了一个数组保存找到的字符和出现的次数,用字符作为键,出现的次数作为值,具体代码如下:

-(void)oc_sumOfCharacters:(NSString*)str{
     //保存每种字符出现的次数  key是字符  value 是字符出现的次数
     NSMutableDictionary * resultDic = [NSMutableDictionary dictionaryWithCapacity:0];
     for (int i = 0; i < str.length; i++) {
          //取出i位置的字符
          NSString * charStr = [self indexCharForStr:str index:i];
          if (charStr == nil) {
               continue;
          }
          //获取所有的key
          NSArray * resultKeys = resultDic.allKeys;
          //判断字符是否在里面
          if ([resultKeys containsObject:charStr]) {
               //存在 取出该字符出现的次数 加1再重新设置
               NSInteger count = [[resultDic objectForKey:charStr] integerValue];
               [resultDic setValue:@(count + 1) forKey:charStr];
          }else{
               //不存在 将该字符存到resultDic中
               [resultDic setValue:@(1) forKey:charStr];
          }
     }
     NSMutableString * resultStr = [NSMutableString string];
     [resultDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
          [resultStr appendFormat:@"%@%@",key,obj];
     }];
     NSLog(@"%@",resultStr);
}

其中对于取出字符串某个位置的字符我是用了字符串截取的方法实现了获取某一位置的字符的方式代码如下:

//取出字符串对应位置的字符
-(NSString *)indexCharForStr:(NSString *)aimStr index:(NSInteger)index{
     if (index >= aimStr.length) {
          return nil;
     }
     if (index > 0) {
          NSString * subToStr = [aimStr substringToIndex:index+1];
          return [subToStr substringFromIndex:index];
     }else{
          return [aimStr substringToIndex:1];
     }
     return nil;
}

输入:AeeDeewzaaaAAA
输出:A4w1D1e4z1a3

想要试的可以直接复制代码进行尝试,有更好的方法也欢迎讨论交流。

上一篇 下一篇

猜你喜欢

热点阅读