want the optimized solution to the solution I already have import java.util.*; public class word { public static void main(String args[]) { String key = "alanlee"; String[] names = { "steve", "alan", "lee", "harvey", "nala" }; List> result = new ArrayList>(); String sortedKey = sortString(key); int keyLength = sortedKey.length(); System.out.println(sortedKey); for (int i = 0; i < names.length - 1; i++) { for (int j = i + 1; j < names.length; j++) { String checkingString = names[i] + names[j]; if (keyLength == checkingString.length()) { if (sortedKey.equalsIgnoreCase(sortString(checkingString))) { List array = new ArrayList(); array.add(names[i]); array.add(names[j]); result.add(array); } } } } System.out.println(result); } private static String sortString(String str){ char[] chars = str.toCharArray(); Arrays.sort(chars); String sortedKey = new String(chars); return sortedKey; }
i want the optimized solution to the solution I already have
import java.util.*;
public class word {
public static void main(String args[]) {
String key = "alanlee";
String[] names = { "steve", "alan", "lee", "harvey", "nala" };
List<List<String>> result = new ArrayList<List<String>>();
String sortedKey = sortString(key);
int keyLength = sortedKey.length();
System.out.println(sortedKey);
for (int i = 0; i < names.length - 1; i++) {
for (int j = i + 1; j < names.length; j++) {
String checkingString = names[i] + names[j];
if (keyLength == checkingString.length()) {
if (sortedKey.equalsIgnoreCase(sortString(checkingString))) {
List<String> array = new ArrayList<String>();
array.add(names[i]);
array.add(names[j]);
result.add(array);
}
}
}
}
System.out.println(result);
}
private static String sortString(String str){
char[] chars = str.toCharArray();
Arrays.sort(chars);
String sortedKey = new String(chars);
return sortedKey;
}
}
Step by step
Solved in 3 steps with 1 images