Here is what I have to do:
Write a function
scramble(str1,str2)that returnstrueif a portion ofstr1characters can be rearranged to matchstr2, otherwise returnsfalse.For example:
str1is'rkqodlw'andstr2is'world'the output should returntrue.str1is'cedewaraaossoqqyt'andstr2is'codewars'should returntrue.str1is'katas'andstr2is'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?