Check string for palindrome

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

    I worked on a solution for a question that was marked as duplicate of this one. Might as well throw it here...

    The question requested a single line to solve this, and I took it more as the literary palindrome - so spaces, punctuation and upper/lower case can throw off the result.

    Here's the ugly solution with a small test class:

    public class Palindrome {
       public static boolean isPalendrome(String arg) {
             return arg.replaceAll("[^A-Za-z]", "").equalsIgnoreCase(new StringBuilder(arg).reverse().toString().replaceAll("[^A-Za-z]", ""));
       }
       public static void main(String[] args) {
          System.out.println(isPalendrome("hiya"));
          System.out.println(isPalendrome("star buttons not tub rats"));
          System.out.println(isPalendrome("stab nail at ill Italian bats!"));
          return;
       }
    }
    

    Sorry that it is kind of nasty - but the other question specified a one-liner.

提交回复
热议问题