gpt4 book ai didi

java - 两个字符串中有多少个字符相同

转载 作者:行者123 更新时间:2023-12-01 12:28:16 25 4
gpt4 key购买 nike

经过多次搜索没有结果,我来寻求您的帮助。我有一个小问题。我有两个字符串:

String values = "acceikoquy";
String values2 = "achips";

我会得到相同数量的字符,所以这里:

3

你知道如何做到这一点吗?

我的代码:

String values = "acceikoquy";
String values2 = "achips";

int test = StringUtils.countMatches(values, values2);

System.out.println(test);

最佳答案

类似这样的事情:

  public static int sameCharsCount(String left, String right, boolean countDuplicates) {
if ((null == left) || (null == right))
return 0;

HashMap<Character, Integer> occurence = new HashMap<Character, Integer>();

for (int i = 0; i < left.length(); ++i) {
Character ch = left.charAt(i);

if (!occurence.containsKey(ch))
occurence.put(ch, 1);
else
occurence.put(ch, occurence.get(ch) + 1);
}

int result = 0;

for (int i = 0; i < right.length(); ++i) {
Character ch = right.charAt(i);

if (occurence.containsKey(ch)) {
result += 1;

if (!countDuplicates || occurence.get(ch) <= 1)
occurence.remove(ch);
else
occurence.put(ch, occurence.get(ch) - 1);
}
}

return result;
}

...

String values = "acceikoquy";
String values2 = "achips";

//TODO: put true or false if you want to count duplicates or not
int result = sameCharsCount(values, values2, true); // <- returns 3

int withDups = sameCharsCount("aaba", "caa", true); // <- 2 (two 'a' are shared)
int noDups = sameCharsCount("aaba", "caa", false); // <- 1 (just a fact, 'a' is shared)

关于java - 两个字符串中有多少个字符相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158441/

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