判断一个字符串是否为回文,以及求一个字符串中最长回文串

本文介绍了一个使用Java编程语言实现的功能,用于检查给定字符串是否为回文串,并找出最长的回文子串。通过遍历字符串并利用自定义函数检查不同长度的子串,最终确定最长的回文子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<pre name="code" class="java"><pre name="code" class="java">package com.four;

public class huiFe1 {
	public static void main(String args[]) {
		String str = "x1234774321sdjh";
		// String str = "x212sdjh";
		String result = "";
		for (int i = 0; i < str.length(); i++) {
			result = check(result, str, i - 1, i + 1);
			result = check(result, str, i, i + 1);
		}
		System.out.println(result);
		if (result == "") {
			System.out.println("这不是个回文串");
		} else {
			System.out.println(str + "中的" + result + "是一个回文");
		}
	}

	public static String check(String result, String str, int start, int end) {
		while (start >= 0 && end < str.length()) {
			if (str.charAt(start) != str.charAt(end)) {
				break;
			}
			start--;
			end++;
		}
		start++;
		end--;
		if (start != end) {
			String temp = str.substring(start, end + 1);
			if (temp.length() > result.length()) {
				result = temp;
			}
		}
		return result;
	}

}





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值