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:
1
2
3
|
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.
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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();
}
}
|
Option 2:
1
2
3
4
5
6
7
8
9
10
11
12
|
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();
}
}
|
Option 3:
1
2
3
4
5
6
7
8
9
10
|
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());
}
}
|
Test cases to validate our solution
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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"));
}
}
|