2つの指定された文字列が互いの順列であるかどうかをチェックできるこのクラスを書きました。しかし、string.indexOf()がO(n)の時間に実行されるため、これはO(n^2)の時間に実行されることは私の理解です。2つの文字列がO(n)時間にお互いの順列であるかどうかを確認する方法はありますか? (java)
どのようにしてこのプログラムを効率化できますか?
import java.util.*;
public class IsPermutation{
public void IsPermutation(){
System.out.println("Checks if two strings are permutations of each other.");
System.out.println("Call the check() method");
}
public boolean check(){
Scanner console = new Scanner(System.in);
System.out.print("Insert first string: ");
String first = console.nextLine();
System.out.print("Insert second string: ");
String second = console.nextLine();
if (first.length() != second.length()){
System.out.println("Not permutations");
return false;
}
for (int i = 0; i < first.length(); i++){
if (second.indexOf(first.charAt(i)) == -1){
System.out.println("Not permutations");
return false;
}
}
System.out.println("permutations");
return true;
}
}
それをより効率的に気にしないではありません正しい。これは 'AAAAT'が' TTTTA'の順列であると言うでしょう。 –
各文字列の各文字の数を数え、それらが等しいかどうかを比較します。 –
状況にもよりますが、ASCIIの範囲内の文字だけであることが分かっているならば、おそらく 'int [256]'を作成し、バケットソートを使って同じ文字の数が同じであるかどうかを確認します – jonhopkins