Returning distinct characters in combined Strings I am trying to return distinct characters from the combination of 2 Strings. The following is my solution which seems to work based on my tests.

Is there a more efficient way of going about this? I have converted the strings to arrays, to sets, to a StringBuilder and back to a String. I'm wondering if I have overcomplicated something which could have been resolved a lot simpler.

public String longest (String s1, String s2) {

    String[] s1Arr = s1.split("");
    String[] s2Arr = s2.split("");

    Set&lt;String&gt; arr1 = new HashSet&lt;&gt;(Arrays.asList(s1Arr));
    Set&lt;String&gt; arr2 = new HashSet&lt;&gt;(Arrays.asList(s2Arr));

    arr1.addAll(arr2);

    StringBuilder sb = new StringBuilder();
    Iterator&lt;String&gt; it = arr1.iterator();
    while (it.hasNext()){
        String element = it.next();
        sb.append(element);
    }

    return sb.toString();
}
What comes to performance, you can improve it significantly:

public static String getDistinctCharString(String s1, String s2) {
    Set&lt;Character&gt; set = new HashSet&lt;&gt;(s1.length() + s2.length());

    char[] chars1 = s1.toCharArray();
    char[] chars2 = s2.toCharArray();

    for (char c : chars1) {
        set.add(c);
    }

    for (char c : chars2) {
        set.add(c);
    }

    StringBuilder sb = new StringBuilder(set.size());

    for (char c : set) {
        sb.append(c);
    }

    return sb.toString();
}


The point is that you deal with characters rather than substrings of length 1. 

My demonstration gives me the following output:




longest() in 2558 ms.
getDistinctCharString() in 342 ms.
Algorithms agree: true




Hope that helps.