• 【转】面试题:最长回文子串


    原文地址:http://blog.csdn.net/v_july_v/article/details/6712171

    查找一个字符串中的最长回文字串,可以使用扩展法。从一个字符开始,向两边扩展,看看最多能到多长,使其保持为回文。

    具体而言,我们可以枚举中心位置,然后再在该位置上用扩展法,记录并更新得到的最长的回文长度,即为所求。代码如下:

    /**  
     *find the longest palindrome in a string, n is the length of string s 
     *Copyright(C) fairywell 2011 
     */  
    int LongestPalindrome(const char *s, int n)  
    {  
       int i, j, max;  
       if (s == 0 || n < 1) return 0;  
       max = 0;  
       for (i = 0; i < n; ++i) { // i is the middle point of the palindrome  
           for (j = 0; (i-j >= 0) && (i+j < n); ++j) // if the length of the palindrome is odd  
               if (s[i-j] != s[i+j]) break;  
           if (j*2+1 > max) max = j * 2 + 1;  
           for (j = 0; (i-j >= 0) && (i+j+1 < n); ++j) // for the even case  
               if (s[i-j] != s[i+j+1]) break;  
           if (j*2+2 > max) max = j * 2 + 2;  
        }  
       return max;  
    }  

    代码稍微难懂一点的地方就是内层的两个 for 循环,它们分别对于以 i 为中心的,长度为奇数和偶数的两种情况,整个代码遍历中心位置 i 并以之扩展,找出最长的回文。

    当然,还有更先进但也更复杂的方法,比如用 s 和逆置 s' 的组合 s$s' 来建立后缀树的方法也能找到最长回文,但构建的过程比较复杂,所以在实践中用的比较少,感兴趣的朋友可以参考相应资料。

  • 相关阅读:
    redis 命令行 操作
    redis php sort 函数
    redis php 实例二
    redis php 实例一
    redis 分布式,主从同步
    inux redis 安装配置, 以及redis php扩展
    linux memcache 安装
    推荐linux命令在线查,简约而不简单
    基于Bootstrap样式的 jQuery UI 控件 (v0.5).
    C语言中文网
  • 原文地址:https://www.cnblogs.com/xmuliushuo/p/3331193.html
Copyright © 2020-2023  润新知