hihoCoder求最长回文字符串

本文介绍了一种使用Java实现的算法,该算法用于找出给定字符串中的最长回文子串。通过双重循环遍历所有可能的子串,并检查每个子串是否为回文来实现。同时提供了一个判断字符串是否为回文的辅助方法。

程序如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {

                String str = "";
                Scanner in = new Scanner(System.in);
                int max=0;      //存放最大长度
                String longestPalindrome="";     //存放最长回文
                str = in.nextLine(); 
                int length = str.length();  

                for (int i = 0; i < length; i++) {         //遍历所有子串
                    for (int j = i + 1; j < length; j++) {  
                        int len = j - i;  
                        String curr = str.substring(i, j + 1);  
                        if (isPalindrome(curr)) {  
                            if (len > max) {  
                                longestPalindrome = curr;  
                                max = len;  
                            }  
                        }  
                    }  
                }  

                return longestPalindrome;  
            }  

            public static boolean isPalindrome(String s) {       //判断是否为回文

                for (int i = 0; i < s.length() - 1; i++) {  
                    if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {  
                        return false;  
                    }  
                }  

                return true;  
            }  
        }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值