首页 > 代码库 > 最大回文长度

最大回文长度

回文                                                                                   

回文串就是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。

code(Java)                                                                            

public class Huiwen {    public static void main(String[] args) {        ArrayList<String> list = new ArrayList<String>();        Scanner in = new Scanner(System.in);        int a = in.nextInt();        while(in.hasNext()) {            list.add(in.next());            a--;            if(a==0)                break;        }        for(int i=0;i<list.size();i++)        {            String s = list.get(i);            int maxlen = maxHuiwen(s);            System.out.println(maxlen);        }    }    public static int maxHuiwen(String string)    {        int max=0;        if(string == null || string == "")            return 0;        char[] a=string.toCharArray();        for (int i = 0; i < string.length(); i++) {            for (int j = 0; i+j<string.length()&&i-j>=0; j++) {                if (a[i-j]!=a[i+j]) {                    break;                }                if (2*j+1>max) {                    max=2*j+1;                }            }            //偶数 
for (int j = 0; i+j+1 < a.length&&i-j>=0; j++) {                if (a[i-j]!=a[i+j+1]) {                    break;                }                if (j*2+2>max) {                    max=j*2+2;                }            }        }        return max;        //System.out.println(max);    }}

code(C++)                                                                            

#include <cstdio>#include <cstring>#include <string.h>char str[1000002 + 1200];int fast(char *p){    int ans = 1;    for (int i = 1; p[i]; ++i)    {        int s = i, e = i, t;        //略过相同的        while (p[e + 1] == p[i]) ++e;        i = e;        //略过相同的之后判断        while (p[s - 1] == p[e + 1]) --s, ++e;        if ((t = e - s + 1) > ans) ans = t;    }    return ans;}int main(){    str[0]=$;    int n;    scanf("%d", &n);    while (n --) {        scanf("%s", str + 1);        printf("%d\n", fast(str));    }    return 0;}

我是天王盖地虎的分割线