美文网首页
查找最大回文子串

查找最大回文子串

作者: 开包辣条压压惊_bda1 | 来源:发表于2017-11-19 21:38 被阅读0次

    package test;import java.util.Stack;

    /** * 查找最大回文字串 * 

     * @author Administrator *

     */

    public class FindMaxRoundString {

    public static void main(String[] args) {

    System.out.println(findMaxRoundString("ababcbadd1234321d"));

    }

    public static String findMaxRoundString(String source) {

    int maxRoundStrLength = 0; // 当前检测到的最大回文

    String maxRoundStr="";

    String tempStr;

    for (int i = 0; i < source.length(); i++) {

    if (source.length() - i > maxRoundStrLength) {

    for (int j = i + 1; j <= source.length(); j++) {

    tempStr = source.substring(i, j);

    if (checkIsRound(tempStr)) {

    if(tempStr.length()>maxRoundStrLength) {

    maxRoundStr = tempStr;

    maxRoundStrLength = tempStr.length();

    }

     }

    }

    }

    return maxRoundStr;

    }

    public static boolean checkIsRound(String str) {

    Stackstack = new Stack();

    char[] chars = str.toCharArray();

    for (int i = 0; i < str.length(); i++) {

    stack.push(String.valueOf(chars[i]));

    }

    StringBuffer dest = new StringBuffer();

    while (!stack.isEmpty()) {

    dest.append(stack.pop());

    }

    return str.equals(dest.toString());

    }

    }

    输出:d1234321d

    相关文章

      网友评论

          本文标题:查找最大回文子串

          本文链接:https://www.haomeiwen.com/subject/etopvxtx.html