判断回文字符串!
这节课课堂测试我们学习了怎样判断回文字符串,首先我学会了递归,用递归解决这个问题是最合适的。递归要有终止条件、调用自己的语句、缩小问题规模。在判断回文字符串这个问题上,我首先将字符串转化为字符数组,定义一个开始的下表,定义一个长度,然后进行比较,之后将开头的坐标向后移,尾坐标向前移,调用自己,终止条件为字符串长度判断小于等于一。
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args){
String str="";
Scanner sc=new Scanner(System.in);
System.out.println("请输入字符串:");
str=sc.nextLine();
boolean judge=huiwen(str,0,str.length());
if(judge==true){
System.out.println("是回文字符串!");
}
else{
System.out.println("不是回文字符串!");
}
}
public static boolean huiwen(String str,int start,int length){
if(length<=1)
return true;
else if(str.toCharArray()[start]==str.toCharArray()[length-1]){
return huiwen(str,start+1,length-1);
}
return false;
}
}
知识兔