3 回答

TA貢獻1886條經驗 獲得超2個贊
您可以使用 aMap<Character,Integer>來計算 a 的每個字符出現的次數String。如果Map兩個Strings 生成的 s 相等,您就會知道相應的Strings 是字謎詞。
例如(這里我使用Map<Integer,Long>而不是Map<Character,Integer>因為它更方便):
String one = "animal";
String two = "manila";
Map<Integer,Long> mapOne = one.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
Map<Integer,Long> mapTwo = two.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println ("Is anagram? " + mapOne.equals(mapTwo));
輸出:
Is anagram? true

TA貢獻1780條經驗 獲得超1個贊
您可以使用 Google guava 的HashMultiSet
.?該equals()
方法正是這樣做的:
比較指定對象與此多重集是否相等。如果給定對象也是多重集并且包含具有相同計數的相同元素(無論順序如何),則返回 true。如果 object 是相同大小的多重集,并且對于每個元素,兩個多重集具有相同的計數,則此實現返回 true。

TA貢獻1828條經驗 獲得超3個贊
除了有序的數據結構之外,還可以動態地對數據進行排序。
由于 Unicode 符號、代碼點比 UTF-16 更好char,我將使用 Unicodeint代替:
int[] canonical(String s) {
return s.codePoints().sorted().toArray();
}
boolean isAnagram(String s, String t) {
return Arrays.equals(canonical(s), canonical(t));
}
boolean isAnagram(int[] s, String t) {
return Arrays.equals(s, canonical(t));
}
添加回答
舉報