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 /*** * The hard part for this one is * 1) in space * 2) white space is size=1, replace string ‘%20‘ is size=3, so cannot * easily replace from begginning. ***/ int spaceCount = 0; //First loop move forward, to count how many white space for (int i = 0; i < length; i++){ if (string[i] == ‘ ‘){ spaceCount++; } } int trueNewLength = length + spaceCount*2; //Second loop move backward to copy the char and replace white space for (int i = length -1; i >= 0; i--){ int newIndex = i + spaceCount * 2; //Consider ‘ ‘ is replaced by ‘0‘, 2 extra char needed to be consider if (string[i] ==‘ ‘){ //Attension: move backward, so ‘0‘ is put first string[newIndex] = ‘0‘; string[newIndex-1] = ‘2‘; string[newIndex-2] = ‘%‘; spaceCount--; } else { string[newIndex] = string[i]; } } return trueNewLength; } }
时间: 2024-12-20 01:20:25