查找最大回文子串

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 一、 1、请用Java写一个冒泡排序方法 【参考答案】 public static void Bubble(int...
    独云阅读 1,412评论 0 6
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,760评论 18 399
  • 【程序1】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔...
    叶总韩阅读 5,165评论 0 41
  • 遇见pretty/文 “初见和告别之间,回想只剩星星点点。曾以为刻骨细节,在骨灰里面怎么捡。” 前几天晚饭后和朋友...
    遇见pretty阅读 2,169评论 7 58