我被要求这样做:
编写函数 scramble(str1,str2),如果 str1 的一部分字符可以重新排列以匹配 str2,则返回 true,否则返回 false。
例如: str1 是“rkqodlw”,str2 是“world”,输出应返回 true。 str1 是“cedewaraaossoqqyt”,str2 是“codewars”应该返回 true。 str1 是“katas”,str2 是“steak”应该返回 false。
仅使用小写字母 (a-z)。不包含标点符号或数字。 需要考虑性能
我的代码是这样的:
导入java.util.ArrayList;
公开课争夺赛{
static ArrayList<String> strTwo = new ArrayList<String>();
static ArrayList<String> strOne = new ArrayList<String>();
static String sub1;
static String sub2;
public static void main (String[] args){
}
public static boolean scramble(String str1, String str2) {
boolean can = false;
int str1length = str1.length();
int looping = 0;
int counter = 0;
//put str1 into arraylist strOne
for (int i = 0; i < str1.length(); i++){
sub1 = str1.substring(i);
for (int k = 0; k<str1.length(); k++){
strOne.add(k, sub1);
}
}
//Put str2 into arraylist strTwo
for (int i = 0; i< str2.length(); i++){
sub2 = str2.substring(i);
for (int k = 0; k < str2.length(); k++){
strTwo.add(k,sub2);
}
}
//now search for str1 in the array strTwo. While loop so that it keeps looping the first for statement
while (looping != str1.length()){
for (int x = 0; x < strOne.size(); x++) {
looping++;
if(strTwo.contains(strOne.get(x))) {
counter++;
}
}
}
if (counter == str2.length()){ //check the counter against the length of str1 (int str1length) and if they are the same then can = true
can = true;
} else {
can = false;
}
return can;
}
}
我的问题是:这段代码是否有效?如果有效,如何才能使其更加高效。我认为这个概念是可行的,但它缺乏优雅性,导致我在代码大战中未能突破编译和执行代码的时间限制。
更新:
根据一些评论,我更新了代码,效果非常好。然而,效率问题仍然存在。这是代码:
公开课争夺赛{
public static boolean scramble(String str1, String str2) {
String temp = str1;
int count = 0;
boolean result = true;
for(int i=0 ; i<str2.length() ; i++){
char c = str2.charAt(i);
if(temp.contains(String.valueOf(c))){
temp = temp.replaceFirst(String.valueOf(c), "");
count++;
}
}
if (count == str2.length()){
result = true;
} else {
result = false;
}
return result;
}
}
如果有人可以帮助我提高此代码的效率,以便在运行测试的效率部分时不会超时,那就太好了。我也发布在这里:https://codereview.stackexchange.com/questions/124172/comparing-two-strings-to-see-if-string-2-is-inside-string-1
最佳答案
创建一个整数数组,足够大以容纳所有可能的字符(英语为 26 个),并初始化为 0。
对于大字符串中的每个字符,获取当前整数并加 1。这表示可以重新排列的所有可能的字符。
对于小字符串中的每个字符,获取当前整数值并减 1。如果在任何时候更新的值为 -1,则无法重新排列较大的字符串。
顺便说一句,出于性能原因,您可能会考虑使用原始字符缓冲区,而不是子字符串或拉出单个字符。
关于java - 有效比较两个 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36242765/