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