名企笔试: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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值