1.1 Char removal

Assumption: The order should remain. String is not null.

Input: String input, String target

Output: new String after deletion

Solution: 1. Use same direction two pointers to create three intervals

2. fast pointer j: pointing at chars being processed

slow pointer i: to its left side (exclusive) are all processed [0, i)

[i, j - 1]: do not care

[j, size - 1]: to be explored

Initializing: i = j = 0

3. Case 1: a[j] should be kept, copy over a[i] = a[j], i++, j++

Case 2: a[j] should be removed, j++

Termination condition: j >= size

public String remove(String input, String target) {
  // corner case
  if (input.isEmpty()) {
    return input;
  }
  char[] array = input.toCharArray();
  // for efficient look-up at String target
  Set<Character> set = buildSet(target);
  int slow = 0;
  for (int fast = 0; fast < input.length; fast++) {
    if (!set.contains(array[fast])) {
      array[slow] = array[fast];
      slow++;
    } 
    return new String(array, 0, slow);
  }
}

private Set<Character> buildSet(String t) {
  Set<Character> set = new HashSet<>();
  for (int i = 0; i < t.length(); i++) {
    set.add(t.charAt(i));
  }
  return set;
}

In-place:

void remove(StringBuilder input) {
  int slow = 0;
  for (int fast = 0; fast < input.length(); fast++)     
    if (!set.contains(input.charAt(fast))) {
      input.setCharAt(slow, input.charAt(fast));
      slow++;
    }
  }
  input.delete(slow, input.length());
}

Last updated

Was this helpful?