ios常见的面试题(一)

//找出字符串不重复字符最大长度
- (int)longestlength:(NSString*)str{
    int a = 0;
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < str.length; i ++) {
        [arr addObject:[str substringWithRange:NSMakeRange(i, 1)]];
    }
    for (int i = 0; i < arr.count - 1; i ++) {
        int index = 0;
        NSString *tempStr = arr[i];
        for (int j = i + 1; j < arr.count ; j ++) {
            
            if ([arr[j] isEqualToString:tempStr]) {
                index = j - i;
                if (index > a) {
                    a = index;
                }
                break;
            }
            else if (j == arr.count - 1) {
                index = j - i;
                if (index > a) {
                    a = index;
                }
            }
        }
    }
    
    return a;
}

//字符串去重
- (NSString*)removeRepeat:(NSString*)str{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < str.length; i ++) {
        if ([arr containsObject:[str substringWithRange:NSMakeRange(i, 1)]]) {
            continue;
        }
        else {
            [arr addObject:[str substringWithRange:NSMakeRange(i, 1)]];
        }
    }
    NSString *tempStr = [arr componentsJoinedByString:@""];
    
    return tempStr;
}
//字符串反转
- (NSString*)fanzhuanString:(NSString*)str{
    if (str.length <= 1) {
        return str;
    }
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < str.length; i ++) {
        [arr addObject:[str substringWithRange:NSMakeRange(i, 1)]];
    }
    //两个指针一前一后开始向中间走
    int a = 0;
    int b = (int)(arr.count - 1);
    //两两交换,如果数组总长度为单数,中间那个不需要管,所以循环次数只需要arr.count / 2;
    for (int i = 0; i < arr.count / 2; i ++) {
        NSString *tempStr = arr[a];
        arr[a] = arr[b];
        arr[b] = tempStr;
        a ++;
        b --;
    }
    return [arr componentsJoinedByString:@""];
}

//有序数组合并(如果是两个无序数组,那就先各自排序,某些排序算法我也自己写了一点,可以找一下我的文章)
- (NSArray*)sortTwoArrOne:(NSArray*)firstArr andTow:(NSArray*)secondArr{
    
    if (firstArr.count == 0) {
        return secondArr;
    }
    if (secondArr.count == 0) {
        return firstArr;
    }
    
    NSMutableArray *muarr = [NSMutableArray array];
    //第一个数组的指针
    int a = 0;
    //第二个数组的指针
    int b = 0;
    //不知道如何说,嘴笨,反正就是每次循环排列好一个数字(主要还是两个指针指向的数值做比较,两个指针向后走)
    for (int i = 0; i < firstArr.count + secondArr.count ; i ++) {
        //前两步判断是为了防止数组越界,总觉得有点蠢
        if (a == firstArr.count) {
            [muarr addObject:secondArr[b]];
            b ++;
        }
        else if (b == secondArr.count) {
            [muarr addObject:firstArr[a]];
            a++;
        }
        else if ([firstArr[a] intValue] <= [secondArr[b] intValue]) {
            [muarr addObject:firstArr[a]];
            a++;
        }
        else {
            [muarr addObject:secondArr[b]];
            b++;
        }
    }
    return muarr;
}

你可能感兴趣的:(ios常见的面试题(一))