Find matching parenthesis

2018/1/10 posted in  codeWars


#import <Foundation/Foundation.h>

int findParenMatch(NSString *s, int n) {
    int res = -1;
    NSString *tmp = [s substringWithRange:NSMakeRange(n, 1)];
    if ([tmp isEqualToString:@"("]) {
        int logF = 0;
        for (int i = n+1; i<s.length; i++) {
            NSString *tmpStrF = [s substringWithRange:NSMakeRange(i, 1)];
            if ([tmpStrF isEqualToString:@"("]) logF++;
            if ([tmpStrF isEqualToString:@")"]) {
                logF--;
                if (logF<0) {
                    res = i;
                    break;
                }
            }
        }
    }else if ([tmp isEqualToString:@")"]){
        int logB = 0;
        for (int i = n-1; i>=0; i--) {
            NSString *tmpStrB = [s substringWithRange:NSMakeRange(i, 1)];
            if ([tmpStrB isEqualToString:@")"]) logB++;
            if ([tmpStrB isEqualToString:@"("]) {
                logB--;
                if (logB<0) {
                    res = i;
                    break;
                }
            }
        }
    }
    return res;
}