Check string for palindrome

前端 未结 30 3501
悲哀的现实
悲哀的现实 2020-11-22 02:47

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction.

To check whether a word is a palindrome I get th

30条回答
  •  离开以前
    2020-11-22 03:13

    Alternatively, recursion.

    For anybody who is looking for a shorter recursive solution, to check if a given string satisfies as a palindrome:

    private boolean isPalindrome(String s) {
        int length = s.length();
    
        if (length < 2) // If the string only has 1 char or is empty
            return true;
        else {
            // Check opposite ends of the string for equality
            if (s.charAt(0) != s.charAt(length - 1))
                return false;
            // Function call for string with the two ends snipped off
            else
                return isPalindrome(s.substring(1, length - 1));
        }
    }
    

    OR even shorter, if you'd like:

    private boolean isPalindrome(String s) {
        int length = s.length();
        if (length < 2) return true;
        return s.charAt(0) != s.charAt(length - 1) ? false :
                isPalindrome(s.substring(1, length - 1));
    }
    

提交回复
热议问题