【发布时间】:2017-02-09 12:35:30
【问题描述】:
我编写了这个类,它可以检查两个给定的字符串是否是彼此的排列。但是,据我了解,这是在 O(n^2) 时间运行的,因为 string.indexOf() 在 O(n) 时间运行。
如何让这个程序更有效率?
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]并使用桶排序来查看它们是否具有相同数量的相同的字符 -
你可以通过切换到 Haskell 来提高效率