lintcode-easy-Space Replacement

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

 

posted @ 2016-03-07 07:29  哥布林工程师  阅读(149)  评论(0编辑  收藏  举报