Valid Parentheses

2017/12/25 posted in  codeWars

#import <Foundation/Foundation.h>

bool validParentheses(NSString *s) {
    // TODO: Return a boolean value indicating whether the
    // order of parentheses in the given string is valid
    if (s.length==0) {
        return 0;
    }
    int sum = 0;
    NSMutableArray *res = @[].mutableCopy;
    for (int i = 0; i<s.length; i++) {
        if ([s characterAtIndex:i]==(unichar)'(') {
            [res addObject:@('(')];
            sum++;
        }
        if ([s characterAtIndex:i]==(unichar)')') {
            if ([[res lastObject] isEqual:@('(')]) {
                [res removeObjectAtIndex:res.count-1];
            }else{
                [res addObject:@(')')];
            }
            sum--;
        }
    }
    if (sum!=0||[res count]!=0) {
        return 0;
    }
    return 1;
}

简化版:


#import <Foundation/Foundation.h>

bool validParentheses(NSString *s) {
  int brackets = 0;
  for (int i = 0; i < [s length]; i++) {
    if ([s characterAtIndex: i] == '(') brackets++;
    else if ([s characterAtIndex: i] == ')') if (--brackets < 0) return false;
  }
  return !brackets;
}