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