私は、文字列の配列で同形のペアの数を返すことを含む、この Java の問題に固執しています。私が書いたコードは、間違った数の同型語ペアを返し続けます。
同形語の定義は次のとおりです。1 つの単語の文字を再マッピングして 2 番目の単語を取得できる場合、2 つの単語は同形語と呼ばれます。文字の再マッピングとは、出現するすべての文字を別の文字に置き換えることを意味します。文字の順序は変更されません。2 つの文字が同じ文字にマップされることはありませんが、文字がそれ自体にマップされる場合があります。たとえば、「abca」と「zbxz」という単語は、「a」を「z」に、「b」を「b」に、「c」を「x」にマッピングできるため、同形です。関数で呼び出す getMap メソッドは含まれていません。getMap メソッドは任意の文字列を入力として受け取り、キーが文字列内の文字であり、対応する値が文字列内の文字の出現回数であるマップを返します。
public class IsomorphicWords {
public int countPairs(String[] words) {
Set <String> pairs = new HashSet<String>();
for (String word:words){
Map noOfOccurencesOfEachLetter= getMap(word);
ArrayList<Integer> valuesFromFirstWord = new ArrayList<Integer>(noOfOccurencesOfEachLetter.values());
Collections.sort(valuesFromFirstWord);
java.util.List<String> list = new ArrayList<String>(Arrays.asList(words));
list.remove(word);
String[] oneLessWord = list.toArray(new String[words.length-1]);
for(String secondWord:oneLessWord){
Map secondNoOfOccurencesOfEachLetter = getMap(secondWord);
ArrayList<Integer> valuesFromSecondWord = new ArrayList<Integer>(secondNoOfOccurencesOfEachLetter.values());
Collections.sort(valuesFromSecondWord);
if (valuesFromFirstWord.equals(valuesFromSecondWord)){
pairs.add(""+word+","+secondWord+"");
}
else{
continue;
}
}
}
return pairs.size()/2;
public Map getMap(String word){
HashMap<String,Integer> noOfOccurencesOfEachLetter= new HashMap<String,Integer>();
for (int i=0;i<word.length();i++){
char letter = word.charAt(i);
String letterInDictionary= Character.toString(letter);
if (noOfOccurencesOfEachLetter.containsKey(letterInDictionary)==true){
int count= noOfOccurencesOfEachLetter.get(letterInDictionary);
noOfOccurencesOfEachLetter.put(letterInDictionary, count+1);
}
else{
noOfOccurencesOfEachLetter.put(letterInDictionary, 1);
}
}
return noOfOccurencesOfEachLetter;
}
}
このコードについてフィードバックをいただければ幸いです。
ありがとう、ジュナイド