美文网首页
无重复的最长字符串

无重复的最长字符串

作者: 小白的天空 | 来源:发表于2021-03-04 21:45 被阅读0次

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

    - (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;
    }

    相关文章

      网友评论

          本文标题:无重复的最长字符串

          本文链接:https://www.haomeiwen.com/subject/gclkqltx.html