最长回文字串(JAVA实现)
来源:互联网 发布:好用的会计软件 编辑:程序博客网 时间:2024/06/18 14:20
题目描述:
给定一个字符串,求它的最长回文字串;
解法:遍历字符串的所有字串,
for(int i=0; i<length; i++) //遍历当前字符串的所有子串{for(int j=i; j<length+1; j++){String str1 = str.substring(i,j);//调用java中截取字符串的方法substring() } }然后对每一个字串进行判断,是否为回文串;
public static boolean Huiwen(String s){ boolean flag=True; int length=str.length(); char str1[]=str.toCharArray(); for(int i=0,j=length-1;i<=j;i++,j--) //判断方式是从两段进行对比,不相同则不问回文串,相同则为回文串 { if(str1[i]!=str1[j]) { flag=false; } } return flag;}最后判断是否为最长回文串;
代码实现如下:
package Test.com;import java.util.Scanner;public class LongestPalindrome {/** * @param args */public static void main(String[] args) {Scanner s = new Scanner(System.in);String str=null; System.out.println("请输入你要输入的字符串:");str = s.next();MaxHuiwen(str);}public static void MaxHuiwen(String str){int length=str.length(); //存储字符串的长度String MaxStr=""; //存储最长的字符串for(int i=0; i<length; i++) //遍历当前字符串的所有子串{for(int j=i; j<length+1; j++){String str1 = str.substring(i,j);//调用java中截取字符串的方法substring()if(Huiwen(str1)&&str1.length()>MaxStr.length()) //如果当前字符串为回文串并且大于MaxStr的长度,则替换当前的回文串{MaxStr=str1;}}}if(MaxStr.length()>=2){System.out.println(MaxStr);}else{System.out.println("没有回文子串");}}public static boolean Huiwen(String str) //判断字符串是否为回文{boolean flag=true;int length=str.length();char str1[]=str.toCharArray();for(int i=0,j=length-1;i<=j;i++,j--){if(str1[i]!=str1[j]){flag=false;}}return flag;}}
编程之法中使用了中心扩展法,以某个字符为中心,判断字符左边和右边是否相同。
public static String MaxHuiWen(String s) { String result=null; int max=0; for(int i=0;i<s.length();i++) { int pLeft=i; int pRight=s.length()-1; while(pLeft>=0&&pRight<=(s.length()-1)&&s.charAt(pLeft)==s.charAt(pRight)) { pLeft++; pRight--; } if(pRight-pLeft-1>max) { max=pRight-pLeft-1; result= s.substring(pLeft+1,pRight-1+1); } pLeft=i-1; pRight=i+1; while(pLeft>=0&&pRight<=(s.length()-1)&&s.charAt(pLeft)==s.charAt(pRight)) { pLeft++; pRight--; } if(pRight-pLeft-1>max) { max=pRight-pLeft-1; result= s.substring(pLeft+1, pLeft); } } return result; }
阅读全文
0 0
- 最长回文字串(JAVA实现)
- 最长回文字串
- 求解最长回文字串
- 最长回文字串
- 最长回文字串
- 最长回文字串
- 最长回文字串
- 最长回文字串
- hihocoder1032:最长回文字串
- 最长回文字串 lintcode
- 求最长回文字串
- 最长回文字串
- 最长回文字串
- 字符串的最长回文字串
- hdu 3068 最长回文字串
- 最长回文字串-manacher算法
- poj_1974,最长回文字串manacher
- C 最长回文字串问题
- JDFZD2总结
- 2729:Blah数集(3.4数据结构之队列)
- numpy中矩阵合并
- nginx + php5.6 + mongo3.2配置安装php mongo扩展
- Unity 算法功能 日記
- 最长回文字串(JAVA实现)
- 找不到或无法加载主类
- NYOJ 中缀式变成后缀式(栈)
- python取数作为临时极大值(极小值)
- hdu1598贪心+并查集的巧妙用法
- centos7 下因/etc/rc.d/rc.local文件出错导致系统起不来
- 剑指offer——二叉树的镜像
- Linux命令详解
- 《好未来编程题》n个数里最小的k个