Follow that Spy

2017/12/23 posted in  codeWars

自己的麻烦些的代码:用了NSMapTable

#import <Foundation/Foundation.h>
NSString *findRoutes(NSArray *routes){
    if ([routes count]==1) {
        return [NSString stringWithFormat:@"%@, %@",routes[0][0],routes[0][1]];
    }
    NSMapTable *map = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableWeakMemory];
    NSMapTable *tol = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory valueOptions:NSMapTableWeakMemory];
    for (NSArray *tmp in routes) {
        [map setObject:tmp[1] forKey:tmp[0]];
        for (NSString* tmpTol in tmp) {
            if ([tol objectForKey:tmpTol]) {
                [tol setObject:@"1" forKey:tmpTol];
            }else{
                [tol setObject:@"0" forKey:tmpTol];
            }
        }
    }
    NSString *str = @"";
    NSString *end = @"";
    NSEnumerator *enumerator = [tol keyEnumerator];
    for (NSString *tmp in enumerator) {
        if ([[tol objectForKey:tmp] isEqualToString:@"0"]) {
            if (![map objectForKey:tmp]) {
                end = tmp;
                continue;
            }
            str = tmp;
        }
    }
    NSString *res = @"";
    res = [res stringByAppendingFormat:@"%@, ", str];
    while ([map objectForKey:str]) {
       res =  [res stringByAppendingFormat:@"%@, ", [map objectForKey:str]];
       str = [map objectForKey:str];
        if ([[map objectForKey:str] isEqualToString:end]) {
            res = [res stringByAppendingString:end];
            break;
        }
    }
    return res;
}

别人的简短代码:

#import <Foundation/Foundation.h>
NSString *findRoutes(NSArray *routes){

    NSMutableArray * routesM = [routes mutableCopy];
    NSMutableArray * answer = [@[routes[0][0]] mutableCopy];
    do{
        for(int i = (int)routesM.count - 1; i >= 0; i--){
            if([[answer lastObject] isEqualToString:routesM[i][0]]){
                [answer addObject:routesM[i][1]];
                [routesM removeObjectAtIndex:i];
            } else if([[answer firstObject] isEqualToString:routesM[i][1]]){
                [answer insertObject:routesM[i][0] atIndex:0];
                [routesM removeObjectAtIndex:i];
            }
        }
    } while (routesM.count > 0);
    return [answer componentsJoinedByString:@", "];
}