首先介绍下什么是回文字符串,回文字符串就是关于中心对称的字符串,比如字符串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;
}
}
本文介绍了回文字符串的概念及两种判断方法:一是通过遍历字符串左右部分进行比较;二是利用StringBuilder类的reverse()方法反转字符串右侧部分,再与左侧部分比较。这两种方法均能有效判断一个字符串是否为回文。
2631

被折叠的 条评论
为什么被折叠?



