Remove duplicate characters from 2 lines

I need to remove duplicate characters from a string. I achieved this with a bitset like this

private static String removeDup(String s1, String s2) {
    BitSet bitSet = new BitSet(26);
    char[] s1Chars = s1.toCharArray();

    for (char s1Char : s1Chars) {
        bitSet.set(s1Char);
    }

    char[] s2Chars = s2.toCharArray();
    StringBuilder sb = new StringBuilder();
    for (char s2Char : s2Chars) {
        if (bitSet.get(s2Char)) {
            //System.out.println("Duplicate " + s2Char);
        } else {
            sb.append(s2Char);
        }
    }

    return sb.toString();
}

Although this method works, is there a better and better way to do it in terms of the complexity of time and space? Thanks

eg.

  • Input: "hello", "world"
  • Output: wrd
+4
source share
1 answer

, , , BMP. , a char 97. BitSet, 26, ; 256 .

, CJK, 8 BitSet.

, ​​ Set<Character>, , O (n) O (n log n).

- . . , :

private static String removeDup(String s1, String s2) {
    Set<Integer> points = s1.codePoints().collect(Collectors.toSet());
    return s2.codePoints().parallel().filter(c->!points.contains(c))
        .collect(StringBuilder::new, StringBuilder::appendCodePoint,
            StringBuilder::append).toString();
}

BMP.

+1

All Articles