Boolean (^isValid)(NSString *string) = ^Boolean(NSString *string) {
NSMutableArray *stack = [NSMutableArray new];
NSDictionary *dic = @{@"(":@")",@"[":@"]",@"{":@"}"};
for (int i = 0; i < string.length; i++) {
NSString *tmp = [string substringWithRange:NSMakeRange(i, 1)];
if (dic[tmp]) {
[stack addObject:tmp];
continue;
}
for (NSString *key in dic.allKeys) {
NSString *value = dic[key];
if ([value isEqualToString:tmp]) {
if (![stack.lastObject isEqualToString:key]) {
return false;
}
[stack removeLastObject];
break;
}
}
}
return ![stack count];
};
- true: isValid(@"{[]}");
- true: isValid(@"{[([{({})}])]}");
- false: isValid(@"{]}");
- true: isValid(@"{(dad)[3223]}");