zoukankan      html  css  js  c++  java
  • [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
        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);
      }
    }
  • 相关阅读:
    Django 框架
    Git 教程
    Vue详解
    pycharm激活码
    通过元类创建一个Python类
    re模块
    selenium模块
    Beautifulsoup模块基础详解
    requests库
    Urllib库
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12777409.html
Copyright © 2011-2022 走看看