1

我写了这个简单的函数(用Java)来重新排列给定的字母String以产生回文,或者如果不可能,就打印-1并返回。

出于某种原因,我无法弄清楚为什么这不起作用(因为它没有通过自动评分脚本)。我测试了我能想到的每一个案例,它确实通过了。

谁能提供一些对此的见解?谢谢!

/**
 * Pseudo-code:
 *      (0) Compute the occurrences of each characters. 
 *      (0')(Also remember how many groups of characters have an odd number of members
 *      (1) If the number remembered above is greater than 1
 *          (meaning there are more than one group of characters with an odd
 *           number of members),
 *          print -1 and return (no palindrome!)
 *      (2) Else, for each group of character
 *              - if the number of member is odd, save it to a var called 'left'
 *              - put a char from the group at the current position, and 
 *                another one at postion [len - cur -1].
 *      (3) If a variable 'left' is defined, put it in the middle of the string
 *      
 * @param wd 
 */

private static void findPalin(String wd)
{
    if (wd.isEmpty())
    {
        // Empty String is a palindrome itself!
        System.out.println("");
        return;
    }
    HashMap<Character, Integer> stats = new HashMap<Character, Integer>();

    int len = wd.length();
    int oddC = 0;
    for (int n = 0; n < len; ++n)
    {
        Integer prv = stats.put(wd.charAt(n), 1);
        if (prv != null)
        {
            if (prv % 2 == 0)
                ++oddC;
            else
                --oddC;
            stats.put(wd.charAt(n), ++prv);
        }
        else
            ++oddC;
    }

    if (oddC > 1)
        System.out.println(-1);
    else
    {
        int pos = 0;
        char ch[] = new char[len];
        char left = '\0';

        for (char theChar :  stats.keySet())
        {

            Integer c = stats.get(theChar);

            if (c % 2 != 0)
            {
                left = theChar;
                --c;
            }

            while (c > 1)
            {
                ch[len - pos - 1] = ch[pos] = theChar;
                ++pos;
                --c;
            }

        }
        if (left != '\0')
            ch[(len - 1) / 2] = left;

        for (char tp : ch)
            System.out.print(tp);
        System.out.println();
    }
}
4

0 回答 0