java判断回文字符串的方法

本文介绍了回文字符串的概念及两种判断方法:一是通过遍历字符串左右部分进行比较;二是利用StringBuilder类的reverse()方法反转字符串右侧部分,再与左侧部分比较。这两种方法均能有效判断一个字符串是否为回文。

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

首先介绍下什么是回文字符串,回文字符串就是关于中心对称的字符串,比如字符串ABCCBA、QWEWQ等等,都是回文字符串
思路一:将一个字符串分为左右两部分,然后将左部分从位置0开始遍历,而右部分则从尾部开始遍历,然后进行比较,如果出现不等的情况则不是回文字符串,如果遍历完都是相等的则是回文字符串,下面是代码展示

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main{
	public static void main(String[] args) throws IOException{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder strB=new StringBuilder(br.readLine());
		System.out.println("输出的字符串是否为回文字符串:"+judgment(strB));
	}
	public static boolean judgment(StringBuilder strB){
		//n为每部分的长度
		int n=strB.length()/2;
		String strLeft=strB.substring(0,n);
		String strRight;
		if(strB.length()%2==0){
			strRight=strB.substring(n);
		}else{
			strRight=strB.substring(n+1);
		}
		//左部分从0开始遍历,右部分从尾部开始遍历
		for(int i=0;i<n;i++){
			if(strLeft.charAt(i)!=strRight.charAt(n-i-1)){
				return false;
			}
		}
		return true;
	}
}

思路二:利用StringBuilder类的reverse()方法,将字符串右边部分进行反转,如果左右两部分相等则为回问字符串,代码如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Main2{
	public static void main(String[] args) throws IOException{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringBuilder strB=new StringBuilder(br.readLine());
		System.out.println("输出的字符串是否为回文字符串:"+judgment(strB));
	}
	public static boolean judgment(StringBuilder strB){
		int n=strB.length()/2;
		StringBuilder strLeft=new StringBuilder(strB.substring(0,n));
		StringBuilder strRight=new StringBuilder();
		if(strB.length()%2==0){
			strRight=new StringBuilder(strB.substring(n));
		}else{
			strRight=new StringBuilder(strB.substring(n+1));
		}
		strRight.reverse();
		if(String.valueOf(strLeft).equals(String.valueOf(strRight))) return true;
		else return false;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值