Check string for palindrome

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

    I'm new to java and I'm taking up your question as a challenge to improve my knowledge.

    import java.util.ArrayList;
    import java.util.List;
    
    public class PalindromeRecursiveBoolean {
    
        public static boolean isPalindrome(String str) {
    
            str = str.toUpperCase();
            char[] strChars = str.toCharArray();
    
            List word = new ArrayList<>();
            for (char c : strChars) {
                word.add(c);
            }
    
            while (true) {
                if ((word.size() == 1) || (word.size() == 0)) {
                    return true;
                }
                if (word.get(0) == word.get(word.size() - 1)) {
                    word.remove(0);
                    word.remove(word.size() - 1);
                } else {
                    return false;
    
                }
    
            }
        }
    }
    
    1. If the string is made of no letters or just one letter, it is a palindrome.
    2. Otherwise, compare the first and last letters of the string.
      • If the first and last letters differ, then the string is not a palindrome
      • Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.

提交回复
热议问题