字符串替换-剑指offer5题

题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如,输入"we are happy",则输出"we%20are%happy"

正常的思想是正向替换,不断的挪动指针,这样会使时间复杂度在O(n2) ,这时需要逆向思维,先讲偏移量算好,这样会减少挪动指针的次数


void repStr(char repStr[],int length) {
    
    if (repStr == nullptr || length <= 0) {
        return;
    }
    
    int orignLen = 0;
    int numberofBank = 0;
    int i = 0;
    while (repStr[i] != '\0') {
        ++ orignLen;
        if (repStr[i] == ' ') {
           ++ numberofBank;
        }
        ++ i;
    }
    
    int newLen = orignLen + numberofBank * 2;
    
    int indexOfOrgin = orignLen;
    int indexOfNew = newLen;
    
    while (orignLen>=0 && indexOfNew > indexOfOrgin) {
        
        if (repStr[indexOfOrgin] == ' ') {
            repStr[indexOfNew --] = '0';
            repStr[indexOfNew --] = '2';
            repStr[indexOfNew --] = '%';
        }else
        {
            repStr[indexOfNew --] = repStr[indexOfOrgin];
        }
        
        -- orignLen;
    }
    
    
}

你可能感兴趣的:(字符串替换-剑指offer5题)