【Lintcode】212. Space Replacement

Title address:

https://www.lintcode.com/problem/space-replacement/description

Given a string, ask to replace all its spaces with " % 20 " "\%20" must be done in-place. You can calculate the length of the replaced string first, and then fill in the string from back to front. code show as below:

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
        // 计算替换后的字符串长度
        int len = 0;
        for (int i = 0; i < length; i++) {
            len += string[i] == ' ' ? 3 : 1;
        }
        
        for (int i = len - 1; i >= 0; i--, length--) {
        	// 如果不等于空格,则直接覆盖,否则依次覆盖'0','2'还有'%'
            if (string[length - 1] != ' ') {
                string[i] = string[length - 1];
            } else {
                string[i--] = '0';
                string[i--] = '2';
                string[i] = '%';
            }
        }
        
        return len;
    }
}

time complexity THE ( n ) O (n)

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105428044