Determine Unique String Characters in Java

1 min read 210 words

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. 

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();
    }
}

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();
    }
}

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());
  }
}

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")); 
    }
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts