美文网首页
最长回文字符串

最长回文字符串

作者: 小白的天空 | 来源:发表于2021-03-06 11:43 被阅读0次

    回文串:正反读都是一样的字符串,如:abba,aba,
    给你一个字符串 s,找到 s 中最长的回文子串。

    - (void)test {
      NSDictionary *dic = [self searchMaxLengthPalindrome:@"abacdcaba"];
      NSLog(@"%@", dic);
    }
    
    - (NSDictionary *)searchMaxLengthPalindrome:(NSString *)str {
      NSInteger maxlength = 0, leftStart = 0;
      for (NSInteger i = 0; i < str.length; i++) {
        NSInteger left = i - 1, right = i + 1, length = 1;
        
        char iC = [str characterAtIndex:i];
        while (left >= 0 && [str characterAtIndex:left] == iC) {
          left--;
          length++;
        }
        while (right < str.length && [str characterAtIndex:right] == iC) {
          right++;
          length++;
        }
        while (left >= 0 && right < str.length && [str characterAtIndex:left] == [str characterAtIndex:right]) {
          left--;
          right++;
          length += 2;
        }
        if (maxlength < length) {
          maxlength = length;
          leftStart = left;
        }
      }
      return
      @{
        @"left": @(leftStart + 1),
        @"right": @(leftStart + maxlength),
        @"lenght": @(maxlength),
        @"value": [[str substringToIndex:(leftStart + 1 + maxlength)] substringFromIndex:leftStart + 1]
      };
    }
    

    输出的结果:
    {
    left = 0;
    lenght = 9;
    right = 9;
    value = abacdcaba;
    }

    相关文章

      网友评论

          本文标题:最长回文字符串

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