(说明:本博客中的题目题目详细说明参考代码均摘自 “何海涛《剑指Offer:名企面试官精讲典型编程题》2012年”)

题目

请实现一个函数,把字符串中的每个空格替换为 "%20" 。例如输入 "We are happy.", 则输出 "We%20are%20happy." 。

进一步详细说明:

在网络编程中,如果 URL 参数中含有特殊字符,如空格、'#'、':' 等,可能导致服务器端无法获得正确的参数值。我们需要这些特殊符号转换成服务器可以识别的字符。转换规则是在 '%' 后面跟上 ASCII 码的两位十六进制的表示。如空格的 ASCII 码是 32,即十六进制的 0x20,因此空格被替换成 "%20" 。再比如 '#' 的 ASCII 码为 35,即十六进制的 0x23,它在 URL 中被替换为 "%32"。再比如 ':' 的 ASCII 码为 50,即十六进制的 0x32,它在 URL 中被替换为 "%32"。

算法设计思想

1. 时间复杂度为 O(n2) 的算法思想

从头到尾,扫描字符串中的每个字符,遇到空格,先将剩余的字符(未遍历到的字符串)整体向后移动2个位置,然后,在空格和其后的2个字符的替换为"%20"。

2. 时间复杂度为 O(n) 的算法思想

先遍历整个字符串,计算字符串中空格的总数,从而可以计算出替换后的字符串长度(根据替换规则,每次替换空格时,都会使字符串的长度增加2)。然后,使用两个指针或索引,从后往前遍历,即初始化指针或索引分别指向替换前和替换后字符串的末尾,循环递减,如遇到空格,则替换为 "%20",从而减少字符串移动的次数,降低时间复杂度。

C++ 实现

#include <iostream>

// Replace blank " " with "%20"
// Note - the 'length' parameter is the maximum length of the array
void ReplaceBlanks(char str[], int length)
{
if (str == NULL || length <= ) // 易漏点
return; // Count the number of blanks
char *pChar = str;
int strLen = ;
int blanksCount = ;
while (*pChar++ != '\0') { // 易错点,容易漏掉指针递增操作,而导致运行时的死循环。
++strLen;
if (*pChar == ' ')
blanksCount++;
}
// Compute the replaced string length
int replacedStrLen = strLen + * blanksCount;
if (replacedStrLen > length) {
std::cout << "The char array is lack of space." << std::endl;
return;
}
// Char pointer initialization
char *pChar2 = str + replacedStrLen - ;
pChar = str + strLen - ;
while (pChar != pChar2) {
// Replace blanks with "%20"
if (*pChar == ' ') {
pChar2 -= ;
*pChar2 = '%';
*(pChar2 + ) = '';
*(pChar2 + ) = '';
} else {
*pChar2 = *pChar;
}
--pChar;
--pChar2;
}
} void unitest()
{
char s[] = "We are happy.";
std::cout << "Before replacing blanks, the string is " << s << std::endl;
ReplaceBlanks(s, );
std::cout << "After replacing blanks, the string is " << s << std::endl;
} int main()
{
unitest(); return ;
}

Python 实现

#!/usr/bin/python
# -*- coding: utf8 -*- # Replace blank " " with "%20"
# Note, the 'string' parameter is Python list type;
# and the 'length' parameter is the maximum length of the array.
def replace_blanks(string, length):
if string == None or length <= 0: # 易漏点
return # Count the number of blanks
blanks_count = string.count(' ')
string_length = len(string) # Compute the replaced string length
replaced_length = string_length + 2 * blanks_count
if replaced_length > length:
return
# Extend the char list length 'string_length' with '' characters
string += ["" for i in range(replaced_length - string_length)] # Replace each blank with "%20"
original_index = string_length - 1
new_index = replaced_length - 1
while new_index != original_index:
if string[original_index] == ' ':
new_index -= 2
string[new_index:new_index+3] = '%20'
else:
string[new_index] = string[original_index]
# Update indexes
new_index -= 1
original_index -= 1 def unitest():
test_string = "We are happy."
string_lst = list(test_string) # 易错点,不能用'str'对象替代,因为 'str' object does not support item assignment 。
print "Before replacing blanks, the string is %s" % ''.join(string_lst)
replace_blanks(string_lst, 100)
print "After replacing blanks, the string is %s" % ''.join(string_lst) if __name__ == '__main__':
unitest()

参考代码

1. targetver.h

#pragma once

// The following macros define the minimum required platform.  The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif

2. stdafx.h

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
// #pragma once #include "targetver.h" #include <stdio.h>
#include <tchar.h> // TODO: reference additional headers your program requires here

3. stdafx.cpp

// stdafx.cpp : source file that includes just the standard includes
// ReplaceBlank.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H
// and not in this file

4. ReplaceBlank.cpp

// ReplaceBlank.cpp : Defines the entry point for the console application.
// // 《剑指Offer——名企面试官精讲典型编程题》代码
// 著作权所有者:何海涛 #include "stdafx.h"
#include <string> /*length 为字符数组string的总容量*/
void ReplaceBlank(char string[], int length)
{
if(string == NULL && length <= )
return; /*originalLength 为字符串string的实际长度*/
int originalLength = ;
int numberOfBlank = ;
int i = ;
while(string[i] != '\0')
{
++ originalLength; if(string[i] == ' ')
++ numberOfBlank; ++ i;
} /*newLength 为把空格替换成'%20'之后的长度*/
int newLength = originalLength + numberOfBlank * ;
if(newLength > length)
return; int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while(indexOfOriginal >= && indexOfNew > indexOfOriginal)
{
if(string[indexOfOriginal] == ' ')
{
string[indexOfNew --] = '';
string[indexOfNew --] = '';
string[indexOfNew --] = '%';
}
else
{
string[indexOfNew --] = string[indexOfOriginal];
} -- indexOfOriginal;
}
} void Test(char* testName, char string[], int length, char expected[])
{
if(testName != NULL)
printf("%s begins: ", testName); ReplaceBlank(string, length); if(expected == NULL && string == NULL)
printf("passed.\n");
else if(expected == NULL && string != NULL)
printf("failed.\n");
else if(strcmp(string, expected) == )
printf("passed.\n");
else
printf("failed.\n");
} // 空格在句子中间
void Test1()
{
const int length = ; char string[length] = "hello world";
Test("Test1", string, length, "hello%20world");
} // 空格在句子开头
void Test2()
{
const int length = ; char string[length] = " helloworld";
Test("Test2", string, length, "%20helloworld");
} // 空格在句子末尾
void Test3()
{
const int length = ; char string[length] = "helloworld ";
Test("Test3", string, length, "helloworld%20");
} // 连续有两个空格
void Test4()
{
const int length = ; char string[length] = "hello world";
Test("Test4", string, length, "hello%20%20world");
} // 传入NULL
void Test5()
{
Test("Test5", NULL, , NULL);
} // 传入内容为空的字符串
void Test6()
{
const int length = ; char string[length] = "";
Test("Test6", string, length, "");
} //传入内容为一个空格的字符串
void Test7()
{
const int length = ; char string[length] = " ";
Test("Test7", string, length, "%20");
} // 传入的字符串没有空格
void Test8()
{
const int length = ; char string[length] = "helloworld";
Test("Test8", string, length, "helloworld");
} // 传入的字符串全是空格
void Test9()
{
const int length = ; char string[length] = " ";
Test("Test9", string, length, "%20%20%20");
} int _tmain(int argc, _TCHAR* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
Test7();
Test8();
Test9(); return ;
}

5. 项目 04_ReplaceBlank 下载

百度网盘: 04_ReplaceBlank.zip

参考资料

[1]  何海涛. 剑指 Offer:名企面试官精讲典型编程题 [M]. 北京:电子工业出版社,2012. 44-48.

替换空格(C++和Python 实现)的更多相关文章

  1. 【剑指Offer】05. 替换空格 解题报告 (Python & C++ & Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人微信公众号:负雪明烛 目录 题目描述 解题方法 方法一:新建可变长度的容器 方法二:原 ...

  2. 替换空格[by Python]

    题目: 请实现一个函数,将一个字符串中的空格替换成“%20”.例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy. 1.使用python自带的repla ...

  3. 《剑指offer》替换空格

    本题来自<剑指offer> 替换空格 题目: 请实现一个函数,将一个字符串中的每个空格替换成“%20”.例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are% ...

  4. LeetCode替换空格

    LeetCode 替换空格 题目描述 请实现一个函数,把字符串 s 中的每个空格替换成"%20". 实例 1: 输入:s = "We are happy." 输 ...

  5. 剑指Offer面试题:3.替换空格

    一.题目:替换空格 题目:请实现一个函数,把字符串中的每个空格替换成"%20".例如输入“We are happy.”,则输出“We%20are%20happy.”. 在网络编程中 ...

  6. 剑指Offer 替换空格

    题目描述 请实现一个函数,将一个字符串中的空格替换成“%20”.例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy.   思路: 替换空格,先遍历一遍记 ...

  7. 剑指Offer:面试题4——替换空格(java实现)

    问题描述:请实现一个函数,把字符串中的每个空格替换成"%20". 例如: 输入:"We are happy." 输出:"We%20are%20happ ...

  8. 【面试题004】c/c++字符串,替换空格

      一,c/c++字符串 1.C/C++中每个字符串都以字符’\0‘作为结尾,这样我们就能很方便地找到字符串的最后尾部. 由于这个原因每个字符串都有一个额外的开销,注意字符串越界的问题: 2.C/C+ ...

  9. 【C语言】字符串替换空格:实现一个函数,把字符串里的空格替换成“%20”

    //字符串替换空格:实现一个函数,把字符串里的空格替换成"%20" #include <stdio.h> #include <assert.h> void ...

随机推荐

  1. css一些常用技巧代码

      图片等比例自动缩放 img{ width: auto; height: auto; max-width: 100%; max-height: 100%; } 多行省略  最后line-clamp设 ...

  2. $bzoj1021-SHOI2008\ Debt$ 循环的债务 $dp$

    题面描述 \(Alice\).\(Bob\)和\(Cynthia\)总是为他们之间混乱的债务而烦恼,终于有一天,他们决定坐下来一起解决这个问题.不过,鉴别钞票的真伪是一件很麻烦的事情,于是他们决定要在 ...

  3. $bzoj1014-JSOI2008$ 火星人$prefix$ $splay$ $hash$

    题面描述 火星人最近研究了一种操作:求一个字串两个后缀的公共前缀.比方说,有这样一个字符串:\(madamimadam\),我们将这个字符串的各个字符予以标号: 序号 1 2 3 4 5 6 7 8 ...

  4. Golang框架beego和bee的开发使用

    Golang语言简洁.明细,语法级支持协程.通道.err,非常诱惑人.平时也看了看Golang的语法,正苦于没有需求,我想把beego的源码搬过来看看. 首先,第一步:beego环境的搭建 在我之前看 ...

  5. crypto-js计算文件的sha256值

    1. 要在浏览器中计算出文件的sha256或md5值,基本思路就是使用HTML5的FileReader接口把文件读取到内存(readAsArrayBuffer),然后获取文件的二进制内容,然后获取文件 ...

  6. gRPC GoLang Test

    gRPC是Google开源的一个高性能.跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x +. gRPC与thrift.avro-rpc.WCF等其实在总体 ...

  7. COALESCE操作符

    一.应用场景 1.购买的零件和本地生产的零件都是零件,尽管多重的实体类型在数据存储上略有不同,但是它们有太多的相同之处,因此通常使用一个表格而不是两个. 所以这是如果我们需要计算零件的实际话费的话,那 ...

  8. Orcale 之基本术语一

    数据字典 数据字典是 Orcale 的重要组成部分.它有一系列的拥有数据库元数据信息的数据字典表和用户可以读取的数据字典视图组成,存放着数据库的有关信息.因此数据字典可以看作一组表和试图的集合.它们存 ...

  9. eclipspe导入hibernate的源代码

    看图:

  10. 阿里云API公共参数的获取

    阿里云公共参数API  https://help.aliyun.com/document_detail/50284.html?spm=5176.10695662.1996646101.searchcl ...