1、思路:如果字符串长度为1或为空串,一定回文;

其他情况使用递归,先比较第一个字符和最后一个字符是否相同,之后将第一个字符位置+1,最后一个字符位置-1,递归调用函数。终止条件为前面字符的位置大于等于后面字符的位置。

2、源代码

import java.util.*;
public class Compare
{  
    public static boolean test(String s,int n,int l){   
        if(n==l||s.length()==0||s.length()==1)
            return true;
        if(s.charAt(n) == s.charAt(l))
        {
           ++n;
           --l;
           return test(s,n,l);
        }
        else
         return false;
    }       
public static void main(String[] args){             
        Scanner in=new Scanner(System.in);            
        System.out.println("请输入一个字符串:");
        String str = in.next();
        int n = 0;     
        int l = str.length() - 1;         
        if(test(str,n,l))
            System.out.println("该字符串回文");  
        else System.out.println("该字符串不回文");   
    } 
}

结果

请输入一个字符串:
tyuyt
该字符串回文

posted on 2019-09-24 20:50  嘻嘻_嘻  阅读(858)  评论(0编辑  收藏  举报