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

String Replacement

时间:2015-11-13 11:38:33      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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
        /***
         * The hard part for this one is 
         * 1) in space
         * 2) white space is size=1, replace string ‘%20‘ is size=3, so cannot
         * easily replace from begginning.
         ***/
        int spaceCount = 0;
        //First loop move forward, to count how many white space
        for (int i = 0; i < length; i++){
            if (string[i] == ‘ ‘){
                spaceCount++;
            }
        }
        
        int trueNewLength = length + spaceCount*2;
        //Second loop move backward to copy the char and replace white space
        for (int i = length -1; i >= 0; i--){
            int newIndex = i + spaceCount * 2; //Consider ‘ ‘ is replaced by ‘0‘, 2 extra char needed to be consider 
            if (string[i] ==‘ ‘){ //Attension: move backward, so ‘0‘ is put first
                string[newIndex] = ‘0‘;
                string[newIndex-1] = ‘2‘;
                string[newIndex-2] = ‘%‘;
                spaceCount--;
            } else {
                string[newIndex] = string[i];
            }
        }
        return trueNewLength;
        
    }
}

 

String Replacement

标签:

原文地址:http://www.cnblogs.com/codingEskimo/p/4961620.html

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