[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.

 
 
Example

Given "Mr John Smith", length = 13.

The string after replacement should be "Mr%20John%20Smith".

Note

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

Challenge

Do it in-place.

 

\\\\\\First, find out how many spaces there are, add 2 extra length to the original length.

record the new length of the return string.

\\\\   Then, keep tracking the string from the end to start.

\\\\ When there is a space,  set them to 02%

 

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(length==0) return 0;
        int len=length;
        for(int i=0;i<length;i++)
        {
            if(string[i]==' ')
            {
                len=len+2;
            }
            
        }
        
        int res=len;
        string[len]='\0';
        --len;
        for(int i=length-1;i>=0;i--)
        {
            if(string[i]==' ')
            {
                string[len--]='0';
                string[len--]='2';
                string[len--]='%';
            }
            else
            {
                string[len--]=string[i];
            }
            
        }
        return res;
    }
}

 

posted on 2015-11-24 02:47  一心一念  阅读(145)  评论(0编辑  收藏  举报

导航