栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

回文数判断与最长回文输出

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

回文数判断与最长回文输出

NC141 判断回文

记录:


下边这个也行:

bool judge(char* str ) {
// write code here
// write code here
char *pe=str;
char *pa=str;
int t=0;
while( *pe != ‘’)
{
t++;
pe++;
}
pe–;
if(t==1)
return true;
while(pa {
if(*pa!=*pe)
return false;
pa++;
pe–;
}
return true;
}

参考链接

NC17 最长回文子串



import java.util.*;

public class Solution {
public int getLongestPalindrome(String A, int n) {
// write code here
//边界条件判断
if (n < 2)
return A.length();
//maxLen表示最长回文串的长度
int maxLen = 0;
for (int i = 0; i < n; ) {
//如果剩余子串长度小于目前查找到的最长回文子串的长度,直接终止循环
// (因为即使他是回文子串,也不是最长的,所以直接终止循环,不再判断)
if (n - i <= maxLen / 2)
break;
int left = i;
int right = i;
while (right < n - 1 && A.charAt(right + 1) == A.charAt(right))
++right; //过滤掉重复的

    //下次在判断的时候从重复的下一个字符开始判断
    i = right + 1;
    //然后往两边判断,找出回文子串的长度
    while (right < n - 1 && left > 0 && A.charAt(right + 1) == A.charAt(left - 1)) {
        ++right;
        --left;
    }
    //保留最长的
    if (right - left + 1 > maxLen) {
        maxLen = right - left + 1;
    }
}
//截取回文子串
return maxLen;
}

}

参考链接:
原文写的特别好,几种解法,有讲解

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337968.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号