码迷,mamicode.com
首页 > 其他好文 > 详细

[Algo] 281. Remove Spaces

时间:2020-04-26 10:56:45      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:ica   ace   input   continue   trail   div   col   pac   put   

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
    if (input == null || input.length() == 0) {
      return input;
    }
    char[] charArr = input.toCharArray();
    int slow = 0;
    for (int i = 0; i < charArr.length; i++) {
      if (charArr[i] == ‘ ‘ && (i == 0 || charArr[i - 1] == ‘ ‘)) {
        continue;
      }
      charArr[slow++] = charArr[i];
    }
    // slow > 0  for case "    "
    if (slow > 0 && charArr[slow - 1] == ‘ ‘) {
      return new String(charArr, 0, slow - 1);
    }
      return new String(charArr, 0, slow);
  }
}

 

[Algo] 281. Remove Spaces

标签:ica   ace   input   continue   trail   div   col   pac   put   

原文地址:https://www.cnblogs.com/xuanlu/p/12777409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!