Write a method to replace all spaces in a string with%20
. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
Given "Mr John Smith"
, length = 13
.
The string after replacement should be "Mr%20John%20Smith"
.
public class Solution { /** * @param string: An array of Char * @param length: The true length of the string * @return: The true length of new string */ public int replaceBlank(char[] string, int length) { // Write your code here if(string == null || string.length == 0) return 0; int space_count = 0; int j = length - 1; while(j >= 0){ if(string[j] == ‘ ‘) space_count++; j--; } int i = length + space_count * 2 - 1; for(j = length - 1; j >= 0; j--){ if(string[j] == ‘ ‘){ string[i--] = ‘0‘; string[i--] = ‘2‘; string[i--] = ‘%‘; } else{ string[i--] = string[j]; } } return length + space_count * 2; } }
时间: 2024-12-26 18:42:19