Check string for palindrome

前端 未结 30 3015
悲哀的现实
悲哀的现实 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.

    0 讨论(0)
  • 2020-11-22 03:20

    Using stack, it can be done like this

    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            String str=in.nextLine();
            str.replaceAll("\\s+","");
            //System.out.println(str);
            Stack<String> stack=new Stack<String>();
            stack.push(str);
            String str_rev=stack.pop();
            if(str.equals(str_rev)){
                System.out.println("Palindrome"); 
            }else{
                 System.out.println("Not Palindrome");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:21

    And here a complete Java 8 streaming solution. An IntStream provides all indexes til strings half length and then a comparision from the start and from the end is done.

    public static void main(String[] args) {
        for (String testStr : Arrays.asList("testset", "none", "andna", "haah", "habh", "haaah")) {
            System.out.println("testing " + testStr + " is palindrome=" + isPalindrome(testStr));
        }
    }
    
    public static boolean isPalindrome(String str) {
        return IntStream.range(0, str.length() / 2)
                .noneMatch(i -> str.charAt(i) != str.charAt(str.length() - i - 1));
    }
    

    Output is:

    testing testset is palindrome=true
    testing none is palindrome=false
    testing andna is palindrome=true
    testing haah is palindrome=true
    testing habh is palindrome=false
    testing haaah is palindrome=true
    
    0 讨论(0)
  • 2020-11-22 03:22

    Try this out :

    import java.util.*;
        public class str {
    
            public static void main(String args[])
            {
              Scanner in=new Scanner(System.in);
              System.out.println("ENTER YOUR STRING: ");
              String a=in.nextLine();
              System.out.println("GIVEN STRING IS: "+a);
              StringBuffer str=new StringBuffer(a);
              StringBuffer str2=new StringBuffer(str.reverse());
              String s2=new String(str2);
              System.out.println("THE REVERSED STRING IS: "+str2);
                if(a.equals(s2))    
                    System.out.println("ITS A PALINDROME");
                else
                    System.out.println("ITS NOT A PALINDROME");
                }
        }
    
    0 讨论(0)
  • 2020-11-22 03:24
    • This implementation works for numbers and strings.
    • Since we are not writing anything, so there is no need to convert the string into the character array.
    public static boolean isPalindrome(Object obj)
    {
        String s = String.valueOf(obj);
    
        for(int left=0, right=s.length()-1; left < right; left++,right--)
        {
            if(s.charAt(left++) != s.charAt(right--))
                return false;
        }
        return true;
    }
    
    0 讨论(0)
  • 2020-11-22 03:26
    public boolean isPalindrome(String abc){
        if(abc != null && abc.length() > 0){
            char[] arr = abc.toCharArray();
            for (int i = 0; i < arr.length/2; i++) {
                if(arr[i] != arr[arr.length - 1 - i]){
                    return false;
                }
            }
            return true;
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题