1. 程式人生 > >212. Space Replacement【LintCode by java】

212. Space Replacement【LintCode by java】

過程 XA 發現 占用 IT -m ava lse ase

Description

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.

If you are using Java or Python,please use characters array instead of string.

Example

Given "Mr John Smith", length = 13.

The string after replacement should be "Mr%20John%20Smith", you need to change the string in-place and return the new length 17.

Challenge

Do it in-place.

解題:給一個字符數組,原地將空格換成 %20 。因為是原地轉換,不能申請額外的空間,那麽只能一步一步往後移動了。因為是把空格轉換成“%20”,空格原本占用一個單位,現在需要占用三個單位,只要把原來空格的後面所有的數都向後移動兩格即可。在移動的過程中,length也隨之變化。代碼如下:

 1 public class Solution {
 2     /*
 3      * @param string: An array of Char
 4      * @param length: The true length of the string
 5      * @return: The true length of new string
 6      */
 7     public int replaceBlank(char[] string, int length) {
 8         // write your code here
 9         for
(int i = 0; i < length; ){ 10 //如果發現空格 11 if(string[i] == ‘ ‘){ 12 for(int j = length-1; j >= i+1; j--){ 13 string[j+2] = string[j]; 14 } 15 string[i++] = ‘%‘; 16 string[i++] = ‘2‘; 17 string[i++] = ‘0‘; 18 length = length+2; 19 }else{ 20 i++; 21 } 22 } 23 return length; 24 } 25 }

212. Space Replacement【LintCode by java】