zoukankan      html  css  js  c++  java
  • 最长回文子串

    题目描述

    对于一个字符串,请设计一个高效算法,计算其中最长回文子串的长度。

    给定字符串A以及它的长度n,请返回最长回文子串的长度。

     
    测试样例:
     
    "abc1234321ab",12

    返回
    :7

    解题思路

    考虑用中心扩展法,即遍历每个字符依次比较其两侧的字符是否相等并记录,分两种情况:子串长度是奇数和偶数。算法时间复杂度为O(N2)

    代码

     1 class Palindrome {
     2 public:
     3     int getLongestPalindrome(string str, int n) {
     4         int count = 0;  
     5         int max = 0; 
     6         if (str.empty() || n<1)
     7             return 0;
     8         for(int i=0;i<n;i++){
     9             for(int j=0;i+j<n&&i-j>=0;j++){
    10                 if(str[i-j]!=str[i+j])
    11                     break;
    12                 count=j*2+1;
    13             }
    14             if(count>max)
    15                 max=count;
    16             for(int j=0;i+j+1<n&&i-j>=0;j++){
    17                 if(str[i-j]!=str[i+j+1])
    18                     break;
    19                 count=j*2+2;
    20             }
    21             if(count>max)
    22                 max=count;
    23         }
    24         return max;  
    25     }
    26 };
  • 相关阅读:
    计算机存储单位
    TcpListener、TcpClient
    JobConf
    JobClient
    python正则方法
    c#列表操作
    C#解析xml
    C#字符串操作函数
    Binding
    Name和:Name
  • 原文地址:https://www.cnblogs.com/wmx24/p/8969497.html
Copyright © 2011-2022 走看看