查找最大回文子串

2017-11-19  本文已影响0人  开包辣条压压惊_bda1

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

上一篇下一篇

猜你喜欢

热点阅读