gpt4 book ai didi

java - CTCI Making Anagrams - 得到不正确的输出

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:39:44 25 4
gpt4 key购买 nike

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

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

最佳答案

您不需要使用子字符串,因为字符串越大,成本越高。您可以使用以下算法。我建议将名称命名为 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 都包含零,则它是变位词,否则就不是。

关于java - CTCI Making Anagrams - 得到不正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52861434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com