美文网首页
匹配两个字符串中的相同部分 并找出最长的相同部分

匹配两个字符串中的相同部分 并找出最长的相同部分

作者: CocoaJason | 来源:发表于2017-06-16 17:08 被阅读28次

    1.获取到某个字符串中所有的子字符串

    -(NSSet *)GetAllSubStrsWithString:(NSString *)aString
    {
        NSMutableSet *set = [NSMutableSet set];
        for (NSUInteger m = 0 ; m < aString.length - 1; m ++)
        {
            for (NSUInteger n = 1 ; n <  aString.length - m; n ++)
            {
                NSRange range = NSMakeRange(m, n);
                NSString *subString = [aString substringWithRange:range];
                [set addObject:subString];
            }
        }
        return  set;
    }
    

    2.算法

    -(NSString *)getResultWithStirng1:(NSString *)string1
                              String2:(NSString *)string2;
    {
        
        NSUInteger maxLegth = MAX(string1.length, string2.length);
        NSString *maxString = string1.length == maxLegth ? string1 : string2;
        NSString *minString = [string1 isEqualToString:maxString] ? string2 : string1;
        if ([maxString containsString:minString])
        {
            return minString;
        }
        NSMutableArray <NSString *>*resultAry = [NSMutableArray array];
        
        NSSet <NSString *>*SubStringset = [self GetAllSubStrsWithString:minString];
        [SubStringset enumerateObjectsUsingBlock:^(NSString * subString, BOOL * _Nonnull stop) {
            if ([maxString containsString:subString])
            {
                [resultAry addObject:subString];
            }
        }];
        
        [resultAry sortUsingComparator:^NSComparisonResult(NSString *result1, NSString *result2) {
            return result1.length > result2.length;
        }];
        NSString *result = resultAry.lastObject;
        return result;
    }
    

    3、测试

    NSString *string1 = @"01dsadasldas2daasdasdadditdddiodsad01dsadasldas2additdddiodsad";
        NSString *string2 = @"0ffdlvdpvdk12addiwwtiodsdas01dsadasldas2additdddiodsad";
        
        NSString *result = [self getResultWithStirng1:string2 String2:string1];
        
        NSLog(@"%@",result);
    

    相关文章

      网友评论

          本文标题:匹配两个字符串中的相同部分 并找出最长的相同部分

          本文链接:https://www.haomeiwen.com/subject/bvsmqxtx.html