使给定字符串成为回文

时间:2013-04-03 23:52:41

标签: java oop recursion palindrome

有人可以讨论和解释我可以修改我的代码以便在这些测试用例中运行的方法......我试图通过替换单词中的一个字母来阻止作为回文的话

期望的测试用例:

Palindromes.isPalindrome2("cat", 'c') => true
Palindromes.isPalindrome2("axaa", 'x') => true
Palindromes.isPalindrome2("12bb", 'b') => true
Palindromes.isPalindrome2("ca", 'c') => true

这就是我到目前为止......

public class Palindromes {

    public static boolean isPalindrome(String word) {
        //Strip out non-alphanumeric characters from string
        String cleanWord = word.replaceAll("[^a-zA-Z0-9]","");
        //Check for palindrome quality recursively
        return checkPalindrome(cleanWord);
    }

    public static boolean isPalindrome2(String word) {
        //Strip out non-alphanumeric characters from string
        String cleanWord = word.replaceAll("[^a-zA-Z0-9]","");
        //Check for palindrome quality recursively
        return checkPalindrome2(cleanWord);
    }

    public static boolean checkPalindrome(String word) {
        if(word.length() < 2) { 
            return true;  
        }
        char first  = word.charAt(0);
        char last   = word.charAt(word.length()-1);
        if(first != last) { 
            return false; 
        }
        else { 
            return checkPalindrome(word.substring(1,word.length()-1));
        }
    }

    public void replace(int first, int last) {
        if(first != last)
        { first = last;}
        else if(last != first) 
        { last = first;}
        }

    public static boolean checkPalindrome2(String word) {
        char special = 0;
        if(word.length() < 2) { 
            return true;  
        }
        char first  = word.charAt(0);
        char last   = word.charAt(word.length()-1);
        if(first != last) { 
            return false; 
        }
        if(first != last)
            return false; 
        else {
            return checkPalindrome2(word.substring(1,word.length()-1));
        }
    }
}

replace()是我处理通配符的尝试,但我似乎无法找到合适的解决方案...所有帮助将不胜感激。感谢...

2 个答案:

答案 0 :(得分:0)

这是我要做的步骤:

  • 将收到的字符串拆分为2个子字符串。第一个字符串front是字符串的前半部分,第二个字符串back是字符串的一半。

示例:

char replacement = 'c';

String input = "aabbcc";
StringBuilder front = new StringBuilder(input.substring(0, input.length()/2));
// Do modulus to not include the odd middle (it mirrors itself)
StringBuilder back = new StringBuilder(input.substring((input.length()/2)+(input.length()%2));
  • 比较两个字符串,如果一个匹配但另一个不匹配则替换。如果两者都不匹配且不是给定的“替换”字符,则返回false。如果您进行多次替换,请返回false(因为这就是您所说的要求)

示例:

int replacements = 0;
for (int i=0; i < front.length(); ++i)
{
    int backIndex = back.length() - i;
    if (front.charAt(i) != back.charAt(backIndex))
    {
        // Characters do not match at all to given replacement
        if ((front.charAt(i) != replacement) &&
            (back.charAt(backIndex) != replacement)
        {
            // Cannot make it 
            // (Or if you want to force it, set both to replacement
            //  by deleting this one if statement)
            return false;
        }
        // Front matches replacement
        else if (front.charAt(i) == replacement)
        {
            // Replace back character with replacement
            back.setCharAt(backIndex, replacement);
            replacements++;
        }
        // Back matches replacement
        else if (back.charAt(backIndex) == replacement)
        {
            // Replace front character with replacement
            front.setCharAt(i, replacement);
            replacements++;
        }
        if (replacements > 1)
        {
            // Can only replace one
            return false;
        }
    }
}

String output = front.toString() + back.toString();

答案 1 :(得分:0)

这是我的代码,它将输入分成两半,并将前半部分与后半部分进行比较。如果它们相等,则输入已经是回文。如果它们不相等,则迭代前半部分,与输入char交换字母以替换,并与每一步的反向后半部分进行比较。然后它做同样的事情,但使用后半部分而不是上半部分:

public class CanMakePalindrome {

    public static void main(String[] args) {
        System.out.println("cat using c: " + canMakePalindrome("cat", 'c'));
        System.out.println("axaa using x: " + canMakePalindrome("axaa", 'x'));
        System.out.println("12bb using b: " + canMakePalindrome("12bb", 'b'));
        System.out.println("ca using c: " + canMakePalindrome("ca", 'c'));
    }

    private static boolean canMakePalindrome(String input, char c) {
        int length = input.length();
        String start = input.substring(0, length/2);
        String end = input.substring(length/2+length%2, length); // need modulus in the case of odd length input

        return (replaceLoop(start,end, c) || replaceLoop(end,start, c));
    }

    private static boolean replaceLoop(String start, String end, char c) {
        if (start.equals(reverse(end))) {
            System.out.println("Input is already a palindrome.");
            return true;
        }

        for (int i=0; i<start.length(); i++) {
            char[] startchars = start.toCharArray();
            char[] endchars = end.toCharArray();
            endchars = reverse(endchars);
            startchars[i] = c;
            if ((new String(startchars).equals(new String(endchars)))) return true;
        }

        return false;
    }

    private static char[] reverse(char[] input) {
        int length = input.length;
        char[] reversed = new char[length];
        for (int i=0;i<length;i++) {
            reversed[length-i-1]=input[i];
        }
        return reversed;
    }

    private static String reverse(String input){
        String reversed = new String(reverse(input.toCharArray())); 
        return reversed;
    }

}

输出:

cat using c: true
axaa using x: true
12bb using b: false
ca using c: true

请注意,仅使用一个字符更改不能将12bb变成回文,因此您的测试用例似乎与仅替换一个字母的规格不符。如果给出一个空字符串作为输入,我的代码也将返回true。