飘飞的海

 

最长回文(找出字符串中对称的子字符串的最大长度)

所谓对称子字符串,就是这个子字符串要么是以其中一个词对称:比如 “aba”, “abcba”;要么就完全对称:比如"abba", "abccba"。

思路:

首先,我们用字符数组 char[] array 来保持这个字符串,假设现在已经遍历到第 i 个字符,要找出以该字符为“中心”的最长对称字符串,我们需要用另两个指针分别向前和向后移动,直到指针到达字符串两端或者两个指针所指的字符不相等。因为对称子字符串有两种情况,所以需要写出两种情况下的代码:

1. 第 i 个字符是该对称字符串的真正的中心,也就是说该对称字符串以第 i 个字符对称, 比如: “aba”。代码里用 index 来代表 i.

    public int oneCenter(char[] array, int index) {
        int length = 1; //最长的子字符串长度
        int j = 1; //前后移动的指针
        while ((index - j) >= 0 && array.length > (index + j) && (array[index - j] == array[index + j])) {
            length += 2;
            j++;
        }        
        return length;
    }

2. 第 i 个字符串是对称字符串的其中一个中心。比如“abba”。

    public int twoCenter(char[] array, int index) {
        int length = 0; //最长的子字符串长度
        int j = 0; //前后移动的指针
        while ((index - j) >= 0 && array.length > (index + j + 1) && (array[index - j] == array[index + j + 1])){
            length += 2;
            j++;
        }
        
        return length;
    }

3.遍历字符串里所有的字符,就可以找出最大长度的对称子字符串

 

    public int maxSubLen(char[] array) {
        if (array.length == 0) return 0;
        int maxLength = 0;
        for (int i = 1; i < array.length; i++) {
            int tmpMaxlen = - 1;
            int len1 = oneCenter(array, i);
            int len2 = twoCenter(array, i);
            tmpMaxlen = (len1 > len2) ? len1 : len2;
            if (tmpMaxlen > maxLength) {
                maxLength = tmpMaxlen;
            }
        }
        return maxLength;
    }

 

posted on 2012-09-21 17:23  飘飞的海  阅读(257)  评论(0编辑  收藏  举报

导航