```java package com.stan.algo.leetcode; public class URLReplaceSpaces { public static void main(String[] args) { System.out.println(replaceSpaces("Mr John Smith ", 13)); System.out.println(replaceSpaces(" ", 5)); } /** * 输入:"Mr John Smith ", 13 * 输出:"Mr%20John%20Smith" * <p> * 输入:" ", * 输出:"%20%20%20%20%20" * * @param S * @param length * @return */ public static String replaceSpaces(String S, int length) { // 转为字符数组 char[] chars = S.toCharArray(); int count = 0; int i = 0; // 时间复杂度 O(n) for (; i < length; i++) { if (chars[i] != 32) { count++; } } char[] chars1; if (count == 0) { chars1 = new char[length * 3]; for (int j = 0; j < length * 3; j++) { if (j % 3 == 0) { chars1[j] = '%'; } else if (j % 3 == 1) { chars1[j] = '2'; } else { chars1[j] = '0'; } } return new String(chars1); } chars1 = new char[3 * (length) - 2 * count]; int index = 0; for (int j = 0; j < length; j++) { if (chars[j] == 32) { chars1[index++] = '%'; chars1[index++] = '2'; chars1[index++] = '0'; } else { chars1[index] = chars[j]; index++; } } return new String(chars1); } }