无重复的最长字符串

给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。

- (void)test {
  NSDictionary *dic = [self searchMaxLengthSubString:@"abcabcdabcbb"];
  NSLog(@"%@", dic);
}

- (NSDictionary *)searchMaxLengthSubString:(NSString *)str {
  NSInteger maxLength = 0, left = 0, right = str.length - 1, lastLeft = 0;
  for (NSInteger i = 0; i < str.length; i++) {
    char ic = [str characterAtIndex:i];
    for (NSInteger j = i - 1; j >= lastLeft; j--) {
      char jc = [str characterAtIndex:j];
      if (jc == ic) {
        NSInteger max = i - lastLeft;
        if (max > maxLength) {
          maxLength = max;
          left = lastLeft;
        }
        right = left + maxLength - 1;
        lastLeft = j + 1;
        break;
      }
    }
  }
  return
  @{
    @"left": @(left),
    @"right": @(right),
    @"lenght": @(right - left + 1),
    @"value": [[str substringToIndex:right + 1] substringFromIndex:left]
  };
}

输出的结果:
{
left = 3;
lenght = 4;
right = 6;
value = abcd;
}

你可能感兴趣的:(无重复的最长字符串)