[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”
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);
  }
}

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/12315638.html
今日推荐