码迷,mamicode.com
首页 > 其他好文 > 详细

[lintcode easy]Space Replacement

时间:2015-11-24 06:16:14      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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

 

[lintcode easy]Space Replacement

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/4990417.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!