名企筆試:Microsoft筆試題(URLify a given string )

Microsoft筆試題(URLify a given string )

題意:
Write a method to replace all the spaces in a string with ‘%20’. You may assume that the string has sufficient space (or allocated memory) at the end to hold the additional characters。
寫一個方法,將字符串中的空格替換成“%20”,字符串具有足夠的空間。(注意最後的空格不進行替換)
輸入描述:
輸入一個T,表示有T組測試數據,每一組測試數據,有兩行第一行表示字符串,第二行是帶有空格的字符串的長度。
輸出描述:
輸出替換後的字符串。
Constraints:
1<=T<=1000
1<=length of result string<=1000
Example:
Input:
2
Mr John Smith
13
Mr Benedict Cumberbatch
25
Output:
“Mr%20John%20Smith”
“Mr%20Benedict%20Cumberbatch
分析:
有一種很“好”的方法,使用C++/Java語言中自帶的函數進行替換,但是庫函數不一定就是最優的方法。還有一種很容易的方法,就是申請一個新的字符串,對其進行賦值,如果遇到空格就用‘%20’替換,時空複雜度都是O(n)。如何更優呢?現在我們應該能想到需要的方法是的空間複雜度降爲O(1)。先不着急,我們先看一個字符串的存儲。例如:
S = “Mr John Smith”
len = 13
這裏寫圖片描述
這裏後面的空格,表示字符串具有足夠的空間,滿足所有的替換。
根據題目的要求我們可以計算出來,最終的字符串的長度,如果我們從後面往前填充即可。
對於上面的例子,final_len = 13 + 2 * k + 1; k = 2表示中間空格的個數,最後的加1用來存儲’\0’。於是得到final_len = 13 + 4 + 1 = 18
從後往前填充,遇到空格,就用’02%’替換。
這裏寫圖片描述
到此,我們得到一個時間複雜度O(n),空間複雜度O(1)的算法。
Code:

/**
 *Author: xiaoran
 *座右銘:既來之,則安之
 */
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<string>
#include<string.h>
using namespace std;

typedef long long LL;

const int MAXN = 1000;
char s[MAXN];
int urlify(char s[]){

    int len = 0;
    for(len = 0;s[len];len++);

    int space_cnt = 0;
    // 計算所有空格的個數
    for(int i=0;i<len;i++){
        if(s[i] == ' ') space_cnt ++;
    }
    //去掉最後空格的情況
    while(s[len-1] == ' '){
        space_cnt --;
        len --;
    }
    // 表示char數組的結尾的'/0'
    int newlen = len + 2 * space_cnt;

    if(newlen > MAXN) return -1;
    int index = newlen;
    s[index --] = '\0';

    for(int i=len-1;i>=0;i--){
        if(s[i] == ' '){
            s[index--] = '0';
            s[index--] = '2';
            s[index--] = '%';
        }
        else{
            s[index--] = s[i];
        }
    }
    return newlen;
}
int main(){
    int t,len;
    scanf("%d\n",&t);
    while(t--){
        //這是一個神奇的用法,受教了
        scanf("%[^\n]s", s);
        scanf("%d\n", &len);
        int newlen = urlify(s);
        for(int i=0;i<newlen;i++){
            cout<<s[i];
        }
        cout<<endl;
    }
}
發佈了258 篇原創文章 · 獲贊 135 · 訪問量 33萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章