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

lintcode-easy-Space Replacement

时间:2016-03-07 07:49:46      阅读:194      评论: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.

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

 

lintcode-easy-Space Replacement

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5249287.html

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