字符串中最长回文,最笨的解法

回文:aba abcba

双重循环遍历字符串,外层从第一个开始找,内层循环从最后一个开始找。当外层的字符和内存循环的字符相等时则组成新的数组,判断是否是回文

public static void main(String[] args) {
    String str = "gcgdecdabcdefgfeh";
    char[] chars = str.toCharArray();
    Map<String,Integer> maxLength = maxLength(chars);
    System.out.println(maxLength);
}
返回结果:{fgf=3, gcg=3, efgfe=5}
//复制出新数组
private static char[] copynew(char[] chars,int start,int end){
    char[] newchars = new char[end-start+1];
    int n = 0;
    for (int i=start;i<=end;i++){
        newchars[n++] = chars[i];
    }
    return newchars;
}

//判断是否是回文
public static boolean check(char[] chars){

    int start = 0;
    int end = chars.length-1;

    while (start<end){

        if(chars[start]==chars[end]){
            start++;
            end--;
        }else {
            return false;
        }
    }
    return true;
}
posted @ 2019-07-17 16:34  努力挣扎的小兵  阅读(264)  评论(0编辑  收藏  举报