Here is what I have to do:
Write a function
scramble(str1,str2)
that returnstrue
if a portion ofstr1
characters can be rearranged to matchstr2
, otherwise returnsfalse
.For example:
str1
is'rkqodlw'
andstr2
is'world'
the output should returntrue
.str1
is'cedewaraaossoqqyt'
andstr2
is'codewars'
should returntrue
.str1
is'katas'
andstr2
is'steak'
should returnfalse
.Only lower case letters will be used (
a-z
). No punctuation or digits will be included. Performance needs to be considered
public class Scramblies {
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;
}
}
My code works perfectly, but the only problem now is efficiency. I am tested against how long it takes to finish the final test class, which times out. I get this:
Process was terminated. It took longer than 10000ms to complete
How can this code be made more efficient to achieve the same result?