1.2 Remove space

Remove all leading/trailing space and duplicated spaces(only keep one) in-place

a b c _ d e _ _ d e _ _

s

f

Assumption: String is not null.

Input: String "_ _ _ abc _ _ de _ _"

Output: String "abc _ de"

Solution: 1. Similar to 1.1, use same direction two pointers, s = f = 0

2. However, there're extra cases to be considered

case 1: if a[fast] = ' '

case 1.1: if fast = 0, don't copy over

case 1.2: if fast != 0,

1.2.1: a[fast - 1] == ' ', dup, don't copy

1.2.2: a[fast - 1] != ' ', , might be b/w chars, copy over

case 2: if a[fast] != ' ', copy over

3: Post-processing: possible trailing space

if (slow > 0 && array[slow - 1] == ' '), slow--

public String removeSpace(String input) {
  // corner case
  if (input.isEmpty()) {
    return input;
  }

  char[] array = input.toCharArray();
  int slow = 0;
  for (int fast = 0; fast < input.length; fast++) {
    if (array[fast] == ' ' && (fast == 0 || array[fast - 1] == ' ')) {
      continue;
    }
    array[slow] = array[fast];
    slow++;
  }
  // post-processing
  if (slow > 0 && array[slow - 1] == ' ') {
    slow--;
  }
  return new String(array, 0, slow);
}

Last updated

Was this helpful?