CTCI Anagrams-获取错误的输出

时间:2018-10-17 18:29:38

标签: java algorithm data-structures stringbuilder anagram

我正在编写一个函数,该函数需要两个字符串,并且应该从一个或两个字符串中删除字符,直到两个字符串具有完全相同的字符为止。然后,我应该返回为实现两者的字谜状态而需要删除的字符数。我得到奇怪的输出(并通过一个测试用例)。谁能告诉我我的功能出了什么问题?

public class Solution {
static int makeAnagram(String a, String b, int aLeng, int bLeng) {
    StringBuilder stringA = new StringBuilder(a);
    StringBuilder stringB = new StringBuilder(b);    

    int result=0;
    for (int i=0; i<stringB.length();i++)
    {
        if (a.contains(b.substring(i)))
            continue;
        else
            stringB.deleteCharAt(i);
    }
    for (int i=0; i<stringA.length();i++)
    {  
        //if(stringB.toString().contains(stringA.toString().substring(i)))
        if (b.contains(a.substring(i)))
             continue;
        else
            stringA.deleteCharAt(i);
    }
    if (stringA.length()==stringB.length())
         result = (aLeng-stringA.length()) + (bLeng-stringB.length());
    else
         result = -1;
    return result;
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
    BufferedWriter bufferedWriter = new BufferedWriter(new                                             FileWriter(System.getenv("OUTPUT_PATH")));

    String a = scanner.nextLine();

    String b = scanner.nextLine();

    int aLeng = a.length();
    int bLeng = b.length();

    int res = makeAnagram(a, b, aLeng, bLeng);

    bufferedWriter.write(String.valueOf(res));
    bufferedWriter.newLine();

    bufferedWriter.close();

    scanner.close();
}
}

测试用例1

Input (stdin)
cde
abc
Your Output (stdout)
4
Expected Output
4

测试用例2

Input (stdin)
fcrxzwscanmligyxyvym
jxwtrhvujlmrpdoqbisbwhmgpmeoke
Your Output (stdout)
-1
Expected Output
30
Compiler Message
Wrong Answer

测试用例3

Input (stdin)
showman
woman
Your Output (stdout)
6
Expected Output
2
Compiler Message
Wrong Answer

1 个答案:

答案 0 :(得分:0)

您不需要使用子字符串,如果使用较大的字符串,子字符串会更昂贵。您可以使用以下算法。我建议命名为checkAnagram而不是makeAnagram

string_counter_map = {}
for char in string1:
    if char in string_counter_map:
        string_counter_map[char] += 1
 for char in string2:
    if char in string_counter_map:
        string_counter_map[char] -= 1
    else:
        string_counter_map[char] = 1

假设string_counter_map的所有字符都包含零,则它是字谜,否则不会。