(说明:本博客中的题目题目详细说明参考代码均摘自 “何海涛《剑指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 <= 0)  // 易漏点return;// Count the number of blankschar *pChar = str;int strLen = 0;int blanksCount = 0;while (*pChar++ != '\0') {   // 易错点,容易漏掉指针递增操作,而导致运行时的死循环。++strLen;if (*pChar == ' ')blanksCount++;}// Compute the replaced string lengthint replacedStrLen = strLen + 2 * blanksCount;if (replacedStrLen > length) {std::cout << "The char array is lack of space." << std::endl;return;}// Char pointer initializationchar *pChar2 = str + replacedStrLen - 1;pChar = str + strLen - 1;while (pChar != pChar2) {// Replace blanks with "%20"if (*pChar == ' ') {pChar2 -= 2;*pChar2 = '%';*(pChar2 + 1) = '2';*(pChar2 + 2) = '0';} else {*pChar2 = *pChar;}--pChar;--pChar2;}
}void unitest()
{char s[100] = "We are happy.";std::cout << "Before replacing blanks, the string is " << s << std::endl;ReplaceBlanks(s, 100);std::cout << "After replacing blanks, the string is " << s << std::endl;
}int main()
{unitest();return 0;
}

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 blanksblanks_count = string.count(' ')string_length = len(string)# Compute the replaced string lengthreplaced_length = string_length + 2 * blanks_countif replaced_length > length:return# Extend the char list length 'string_length' with '' charactersstring += ["" for i in range(replaced_length - string_length)]# Replace each blank with "%20"original_index = string_length - 1new_index = replaced_length - 1while new_index != original_index:if string[original_index] == ' ':new_index -= 2string[new_index:new_index+3] = '%20'else:string[new_index] = string[original_index]# Update indexesnew_index -= 1original_index -= 1def 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 <= 0)return;/*originalLength 为字符串string的实际长度*/int originalLength = 0;int numberOfBlank = 0;int i = 0;while(string[i] != '\0'){++ originalLength;if(string[i] == ' ')++ numberOfBlank;++ i;}/*newLength 为把空格替换成'%20'之后的长度*/int newLength = originalLength + numberOfBlank * 2;if(newLength > length)return;int indexOfOriginal = originalLength;int indexOfNew = newLength;while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal){if(string[indexOfOriginal] == ' '){string[indexOfNew --] = '0';string[indexOfNew --] = '2';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) == 0)printf("passed.\n");elseprintf("failed.\n");
}// 空格在句子中间
void Test1()
{const int length = 100;char string[length] = "hello world";Test("Test1", string, length, "hello%20world");
}// 空格在句子开头
void Test2()
{const int length = 100;char string[length] = " helloworld";Test("Test2", string, length, "%20helloworld");
}// 空格在句子末尾
void Test3()
{const int length = 100;char string[length] = "helloworld ";Test("Test3", string, length, "helloworld%20");
}// 连续有两个空格
void Test4()
{const int length = 100;char string[length] = "hello  world";Test("Test4", string, length, "hello%20%20world");
}// 传入NULL
void Test5()
{Test("Test5", NULL, 0, NULL);
}// 传入内容为空的字符串
void Test6()
{const int length = 100;char string[length] = "";Test("Test6", string, length, "");
}//传入内容为一个空格的字符串
void Test7()
{const int length = 100;char string[length] = " ";Test("Test7", string, length, "%20");
}// 传入的字符串没有空格
void Test8()
{const int length = 100;char string[length] = "helloworld";Test("Test8", string, length, "helloworld");
}// 传入的字符串全是空格
void Test9()
{const int length = 100;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 0;
}

5. 项目 04_ReplaceBlank 下载

百度网盘: 04_ReplaceBlank.zip

参考资料

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

转载于:https://www.cnblogs.com/klchang/p/7501911.html

替换空格(C++和Python 实现)相关推荐

  1. python剑指offer替换空格_《剑指offer》2-替换空格【Java+Python】

    替换空格 1. 题目描述 请实现一个函数,将一个字符串中的空格替换成"%20". 2. 示例 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%2 ...

  2. c语言把下划线换成空格,python - 如何用下划线替换空格,反之亦然?

    python - 如何用下划线替换空格,反之亦然? 我想用字符串中的下划线替换空格来创建漂亮的URL. 例如: "This should be connected" becomes ...

  3. 剑指offer:替换空格

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

  4. 剑指Offer(二):替换空格

    参考链接: https://cuijiahua.com/blog/2017/11/basis_2.html https://blog.csdn.net/wang454592297/article/de ...

  5. ~4.1 剑指 Offer 05. 替换空格

    剑指 Offer 05. 替换空格 题目描述 思路 源代码 题目描述 思路 C++: 在 C++ 语言中, string 被设计成「可变」的类型,因此可以在不新建字符串的情况下实现原地修改. 思路: ...

  6. 剑指offer:面试题05. 替换空格

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

  7. URL化 替换空格

    URL化 替换空格 编写一种方法,将字符串中的空格全部替换为%20.假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的"真实"长度. 示例 1: 输入:"Mr J ...

  8. 替换空格---StringBuilder

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

  9. 字符串一:替换空格()

    /**  * 题目:替换空格()  * 描述:请实现一个函数,将一个字符串中的空格替换成"%20".例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Ar ...

最新文章

  1. 软件构造 第二章 第一节 软件生命周期和版本控制
  2. Linux - 网络相关指令
  3. Windows编程-- 用户方式中线程的同步---关键代码段(临界区)
  4. 北京加强数据中心节能审查,2030年100%利用可再生能源
  5. [No0000166]CPU的组成结构及其原理
  6. 微信上了一个新功能,吐槽的人有点多
  7. 一款社区论坛小程序源码(修复登录图片发布上传问题)
  8. 解决Tomcat.exe或者startup.bat 一闪无法打开的问题
  9. c# npoi 打开已经存在excel_用了这个jupyter插件,我已经半个月没打开过excel了
  10. linux运行级别0-6的各自含义(考试题答案系列)
  11. 辰视携最新3D视觉技术及解决方案参加华南工博会国际机器视觉展
  12. php图书借阅管理系统前台,php图书馆图书借阅管理系统
  13. USB1.1学习笔记
  14. pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn pym
  15. vue项目中/deep/的用法-vue-cli中没法覆盖样式解决方法
  16. 在线解析香港服务器和国内服务器的区别
  17. sql数据库连接字符串(Persist Security Info)
  18. Ignite 数据网格快速学习(一)
  19. 在Windows中安装MinGW-w64最新版本(目前12.1.0)
  20. kml文件转成cvs_如何将excel转换成kml

热门文章

  1. 看见统计——第五章 统计推断:贝叶斯学派
  2. PMSM的发展及研究现状
  3. 如何解决visual studio提示使用_CRT_SECURE_NO_WARNINGS的问题
  4. next和nextLine的使用
  5. 通过金矿模型介绍动态规划
  6. 一位IT新人对工作计划的心得体会
  7. 网页设计作业 开心网旅游(11页) web前端期末大作业 html+css+javascript网页设计实例
  8. 大学物理简明教程重点归纳
  9. python windows api hook_windows hook + pyhook3 + python win32api hook + C 键盘hook
  10. 静脉给药时css,2017年药学专业知识一复习讲义:单室模型静脉滴注给药