Check string for palindrome

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

    I was looking for a solution that not only worked for palindromes like...

    • "Kayak"
    • "Madam"

    ...but as well for...

    • "A man, a plan, a canal, Panama!"
    • "Was it a car or a cat I saw?"
    • "No 'x' in Nixon"

    Iterative: This has be proven as a good solution.

    private boolean isPalindromeIterative(final String string)
        {
            final char[] characters =
                string.replaceAll("[\\W]", "").toLowerCase().toCharArray();
    
            int iteratorLeft = 0;
            int iteratorEnd = characters.length - 1;
    
            while (iteratorEnd > iteratorLeft)
            {
                if (characters[iteratorLeft++] != characters[iteratorEnd--])
                {
                    return false;
                }
            }
    
            return true;
        }
    

    Recursive. I think this solution shouldn't be much worse than the iterative one. Is a little bit crapy we need to extract the cleaning step out of the method to avoid unnecesary procesing.

    private boolean isPalindromeRecursive(final String string)
            {
                final String cleanString = string.replaceAll("[\\W]", "").toLowerCase();
                return isPalindromeRecursiveRecursion(cleanString);
            }
    
    private boolean isPalindromeRecursiveRecursion(final String cleanString)
            {
                final int cleanStringLength = cleanString.length();
    
                return cleanStringLength <= 1 || cleanString.charAt(0) ==
                           cleanString.charAt(cleanStringLength - 1) &&
                           isPalindromeRecursiveRecursion  
                               (cleanString.substring(1, cleanStringLength - 1));
            }
    

    Reversing: This has been proved as a expensive solution.

    private boolean isPalindromeReversing(final String string)
        {
            final String cleanString = string.replaceAll("[\\W]", "").toLowerCase();
            return cleanString.equals(new StringBuilder(cleanString).reverse().toString());
        }
    

    All the credits to the guys answering in this post and bringing light to the topic.

提交回复
热议问题