事情是這樣的:
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)
可能重複http://stackoverflow.com/questions/3985328/checking-if-2-strings-contain-the-same-characters – 2014-10-02 09:57:55
你遇到了什麼問題,當你試圖自己做這個? – EWit 2014-10-02 09:58:06
你試過了什麼? – 2014-10-02 09:58:10