[Algo] 281. Remove Spaces

Given a string, remove all leading/trailing/duplicated empty spaces.

Assumptions:

  • The given string is not null.

Examples:

  • “  a” --> “a”
  • “   I     love MTV ” --> “I love MTV”

Solution 1:

public class Solution {
  public String removeSpaces(String input) {
    // Write your solution here
    int i = 0;
    int slow = 0;
    int count = 0;
    int len = input.length();
    char[] charArr = input.toCharArray();
    while(true) {
      while (i < len && charArr[i] == ' ') {
        i += 1;
      }
      if (i == len) {
        break;
      }
      if (count > 0) {
        charArr[slow++] = ' ';
      }

      while (i < len && charArr[i] != ' ') {
        charArr[slow++] = charArr[i++];
      }
      count += 1;
    }
    return new String(charArr, 0, slow);
  }
}

 

Solution 2:

public class Solution {
  public String removeSpaces(String input) {
    // Write your solution here
    int slow = 0;
    char[] charArr = input.toCharArray();
    for (int i = 0; i < charArr.length; i++) {
      if (charArr[i] == ' ' && (i == 0 || charArr[i - 1] == ' ')) {
        continue;
      }
      charArr[slow++] = charArr[i];
    }
    if (slow > 0 && charArr[slow - 1] == ' ') {
      return new String(charArr, 0, slow - 1);
    }
    return new String(charArr, 0, slow);
  }
}

 

你可能感兴趣的:([Algo] 281. Remove Spaces)