Delete the characters in two strings if the character matches the string

2

I have a problem with Java and it is as follows:

I have these two String :

String string1 = "aabcdef";
String string2 = "abcghi";

And I need to get this "adefghi" .

public static String regenerate(String a, String b)
{
      String common = null;

      common = a.replaceAll("[" + b + "]", "");
      common += b.replaceAll("[" + a + "]", "");

      return common;
}

Where what I want to do is:

a abc def

abc ghi

Leaving only: a def ghi

My problem is that this prints "defghi" , which is a wrong result, can someone help me?

    
asked by Héctor Manuel Martinez Durán 28.03.2018 в 22:02
source

1 answer

3

This is the answer you need, you can try it directly:

import java.util.HashSet;

public class Main {

    public static void main(String[] args) throws InterruptedException {
        String a = "aabcdef";
        String b = "abcghi";
        System.out.println(regenerate(a,b));
        //Thread.sleep(10000000);
    }

    public static String regenerate(String a, String b)
    {
        HashSet<String> yaRetiradas = new HashSet<>();
        for(String letra : a.split("(?!^)")){
            if(!yaRetiradas.contains(letra) && b.contains(letra)){
                a = a.replaceFirst(letra,"");
                b = b.replaceFirst(letra,"");
                yaRetiradas.add(letra);
            }
        }
        return a+b;
    }
}

We are removing characters element by element and we verify that that letter has not been removed before. We remove only the elements repeated once in both chains.

The result is adefghi .

    
answered by 29.03.2018 / 01:01
source