Check string for palindrome

前端 未结 30 3749
悲哀的现实
悲哀的现实 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:29

    You can check if a string is a palindrome by comparing it to the reverse of itself:

    public static boolean isPalindrome(String str) {
        return str.equals(new StringBuilder(str).reverse().toString());
    }
    

    or for versions of Java earlier than 1.5,

    public static boolean isPalindrome(String str) {
        return str.equals(new StringBuffer().append(str).reverse().toString());
    }
    

    EDIT: @FernandoPelliccioni provided a very thorough analysis of the efficiency (or lack thereof) of this solution, both in terms of time and space. If you're interested in the computational complexity of this and other possible solutions to this question, please read it!

提交回复
热议问题