Determine Unique String Characters in Java

The challenge

In this challenge, you will be given two strings a and b and your task will be to return the characters that are not common in the two strings.

For example:

solve("xyab","xzca") = "ybzc" --The first string has 'yb' which is not in the second string. --The second string has 'zc' which is not in the first string.
Code language: JavaScript (javascript)

Notice also that you return the characters from the first string concatenated with those from the second string.

The solution in Java code

Option 1:

class Solution { public static String solve(String a, String b){ StringBuilder sb = new StringBuilder(); for (int i=0; i<a.length(); i++) { if (!b.contains(""+a.charAt(i))) sb.append(a.charAt(i)); } for (int i=0; i<b.length(); i++) { if (!a.contains(""+b.charAt(i))) sb.append(b.charAt(i)); } return sb.toString(); } }
Code language: Java (java)

Option 2:

class Solution{ public static String solve(String a, String b){ StringBuilder sb = new StringBuilder(); for (String s : (a+b).split("")) if (a.contains(s) ^ b.contains(s)) sb.append(s); return sb.toString(); } }
Code language: Java (java)

Option 3:

import static java.util.stream.Collectors.joining; import static java.util.stream.Stream.of; interface Solution { static String solve(String a, String b) { return of((a + b).split("")) .filter(c -> a.contains(c) ^ b.contains(c)) .collect(joining()); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; public class SolutionTest{ @Test public void basicTests(){ assertEquals("ybzc",Solution.solve("xyab","xzca")); assertEquals("ybbzc",Solution.solve("xyabb","xzca")); assertEquals("abcdxyz",Solution.solve("abcd","xyz")); assertEquals("zca",Solution.solve("xxx","xzca")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments