字母数字混合排序

僵尸学编程 2016-10-09 05:51:33
最近面试,遇到这样的一个问题 把以下的字符串排序 a1 b2 a22 a11 a21 c10 a23 a33 a30 a31 a32 排成以下的顺序 a1 b2 c10 a11 a21 a22 a23 a30 a31 a32 a33 各位大神,请指教 第一次发帖,有什么不好的请见谅!
...全文
747 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
loveason? 2018-01-03
  • 打赏
  • 举报
回复
分成字母和数字两部分,用基数排序
不担心 2016-10-09
  • 打赏
  • 举报
回复
没看出什么特别的规律,我觉得应该就是把首字母去掉后,根据后面的数字从大到小排序. 不考虑性能,只实现结果,可以用我这个方法
    NSString *str = @"a1 b2 a22 a11 a21 c10 a23 a33 a30 a31 a32";
    NSArray *originArray = [str componentsSeparatedByString:@" "];
    NSMutableArray *numAr = [[NSMutableArray alloc] initWithCapacity:originArray.count];
    [originArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *s = (NSString *)obj;
        NSString *subs = [s substringFromIndex:1];
        NSDictionary *dict =@{@"index":[@(idx) stringValue],@"value":@([subs intValue])};
        [numAr addObject:dict];
    }];
    
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"value" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sorter count:1];
    NSArray *tempArray = [numAr sortedArrayUsingDescriptors:sortDescriptors];
    
    NSMutableArray *sortedArray = [[NSMutableArray alloc] initWithCapacity:originArray.count];
    [tempArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *dict = (NSDictionary *)obj;
        int index = [dict[@"index"] intValue];
        NSString *str = originArray[index];
        [sortedArray addObject:str];
    }];
    
    NSLog(@"%@",sortedArray);
运行结果: 2016-10-09 23:38:35.594 temp[19198:244055] ( a1, b2, c10, a11, a21, a22, a23, a30, a31, a32, a33 )

29,028

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧