Creating a recursive method for Palindrome

前端 未结 21 1991
野的像风
野的像风 2020-12-03 06:28

I am trying to create a Palindrome program using recursion within Java but I am stuck, this is what I have so far:

 public static void main (String[] args){
         


        
21条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 06:45

    Palindrome example:

    static boolean isPalindrome(String sentence) {
    
        /*If the length of the string is 0 or 1(no more string to check), 
         *return true, as the base case. Then compare to see if the first 
         *and last letters are equal, by cutting off the first and last 
         *letters each time the function is recursively called.*/
    
        int length = sentence.length();
    
        if (length >= 1)
            return true;
        else {
            char first = Character.toLowerCase(sentence.charAt(0));
            char last = Character.toLowerCase(sentence.charAt(length-1));
    
            if (Character.isLetter(first) && Character.isLetter(last)) {
                if (first == last) {
                    String shorter = sentence.substring(1, length-1);
                    return isPalindrome(shorter);
                } else {
                    return false;
                }
            } else if (!Character.isLetter(last)) {
                String shorter = sentence.substring(0, length-1);
                return isPalindrome(shorter);
            } else {
                String shorter = sentence.substring(1);
                return isPalindrome(shorter);
            }
        }
    }
    

    Called by:

    System.out.println(r.isPalindrome("Madam, I'm Adam"));
    

    Will print true if palindrome, will print false if not.

    If the length of the string is 0 or 1(no more string to check), return true, as the base case. This base case will be referred to by function call right before this. Then compare to see if the first and last letters are equal, by cutting off the first and last letters each time the function is recursively called.

提交回复
热议问题