-1

Saying that there are String A = "aabbccdd" and String B = "abcd", is there any way to remove the matching characters of String B towards String A for only one time?

Expected output is A = "abcd".

I know it will solve the problem when using for loops, but is there any simpler way to do it? For example, using replaceAll or regular expressions?

YeonSoo
  • 33
  • 7

2 Answers2

1

you can use the regex for that

A = A.replaceAll("([a-z]+)\1","");

can find out more about regex here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Bryan Motta
  • 131
  • 7
  • Although this works for the example given, I think the example is an edge case; eg if A was `abbcdacd` the result should be `bacd` – Bohemian Nov 28 '21 at 20:33
1

you can use distinct() method

public static void main(String[] args) {
        String str = "aabbccdd";
        String result = str.chars().distinct().boxed()
                .map(c -> (char) (c.intValue()))
                .map(String::valueOf)
                .collect(Collectors.joining());
        System.out.println(result);
    }