劍指Offer——面試題4:替換空格

替換空格


題目:請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。

輸入:”We Are Happy.”

輸出:”We%20Are%20Happy.”

思路:1、先遍歷一遍字符串,找到原字符數組的長度和空格的個數
2、然後對於每個空格爲字符數組長度+2,因爲原空格佔1個字符,而加的%20是佔3個字符
3、然後設置2個指針,一個指向新的位置,一個指向老的位置,依次進行復制,遇到空格時,老位置只減1,而新位置依次加入‘0’、‘2’、‘%’即可
4、最終只需要遍歷2次該數組,即時間複雜度爲O(n)

/*
實現:替換空格,例子是"we are happy.",空格替換爲'%20'
*/

#include<iostream>
#include<string>
using namespace std;

//length表示字符型數組最大的長度
void ReplaceBlank(char c[],int length){
    if (c == NULL){
        return;
    }
    int blankNumber = 0;
    int originalLength = 0;
    int i = 0;
    while (c[i] != '\0'){
        originalLength++;
        if (c[i] == ' '){
            blankNumber++;
        }
        i++;
    }
    if (originalLength <= 0){
        return;
    }
    int newLength = originalLength + blankNumber * 2;
    if (newLength > length){
        return;
    }
    int newIndex = newLength;
    int originIndex = originalLength;
    while (originIndex >= 0){
        if (c[originIndex] != ' '){
            c[newIndex--] = c[originIndex--];
        }
        else{
            c[newIndex--] = '0';
            c[newIndex--] = '2';
            c[newIndex--] = '%';
            originIndex--;
        }
    }
    cout << c;
}

int main(){
    char c[] = "we are happy.";
    ReplaceBlank(c,100);
    system("pause");
    return 0;
}
發佈了50 篇原創文章 · 獲贊 45 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章