I've been doing lately CodeWars and here's my working code for this challenge.
The challenge :
Take 2 strings s1 and s2 including only letters from a to z. Return a new sorted string, the longest possible, containing distinct letters, - each taken only once - coming from s1 or s2.
My code :
public static String longest(String s1, String s2) {
StringBuilder sb = new StringBuilder();
sb.append(s1).append(s2);
String s = sb.toString();
String result = "";
for (int i = 0; i < s.length(); i++) {
if (!result.contains(String.valueOf(s.charAt(i)))) {
result += s.charAt(i);
}
}
char[] ch = result.toCharArray();
Arrays.sort(ch);
return String.valueOf(ch);
}
Is there a way to skip all the transformations to arrays and then back to a String? I found it quite useful to use Arrays.sort because I didnt have to do another loop to sort chars in a String (dont think there is a StringBuilder method to sort chars as String is immutable, right?) Saw other solutions and many of them use streams but I havent learned about them yet so not trying to use them. Also I think there is no point in assigning String s becasue I can use sb.length() if a for loop and avoid another variable, right?