【Lintcode】212。スペース交換

タイトルアドレス:

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

文字列が与えられたら、そのすべてのスペースを 20 「\%20」 はインプレースで実行する必要があります。最初に、置き換えられた文字列の長さを計算し、次に文字列を後ろから前へと入力します。コードは次のとおりです。

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

時間の複雑さ O(n)

公開された387元の記事 ウォンの賞賛0 ビュー10000 +

おすすめ

転載: blog.csdn.net/qq_46105170/article/details/105428044