#212 Space Replacement
来源:互联网 发布:nginx视频教程 尚硅谷 编辑:程序博客网 时间:2024/04/29 04:00
题目描述:
Write a method to replace all spaces in a string with %20
. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
Notice
If you are using Java or Python,please use characters array instead of string.
Given "Mr John Smith"
, length = 13
.
The string after replacement should be "Mr%20John%20Smith"
, you need to change the string in-place and return the new length 17
.
Do it in-place.
既然要做in-place work,那么我们首先要知道new length是多长,这样我们可以找到新string的尾巴在哪里,然后从尾巴开始做新的string,就可以做到in-place了。求新的length也很简单,先从旧的string计算一共有多少个space,然后new length = length + 2 * num of spaces就可以了。
Mycode(AC = 12ms):
class Solution {public: /** * @param string: An array of Char * @param length: The true length of the string * @return: The true length of new string */ int replaceBlank(char string[], int length) { // Write your code here // get the number of spaces int num_space = 0; for (int i = 0; i < length; i++) { if (string[i] == ' ') { num_space++; } } // get new length according to number of spaces int new_length = length + num_space * 2; int r = length - 1; // starting from end of new string for (int i = new_length - 1; i >= 0; i--) { if (string[r] == ' ') { string[i] = '0'; string[i - 1] = '2'; string[i - 2] = '%'; i -= 2; } else { string[i] = string[r]; } r--; } return new_length; }};
- #212 Space Replacement
- Space Replacement
- [刷题]Space Replacement
- [Lintcode]Space Replacement
- LintCode_212 Space Replacement
- Space Replacement 解题报告
- Replacement
- 212.Space Replacement-空格替换(容易题)
- page replacement
- A. Replacement
- C. Replacement
- Page Replacement
- Integer Replacement
- CodeForces570C - Replacement
- Integer Replacement
- Integer Replacement
- space
- space
- iOS开发:自定义framework并打包
- 失败的自定义View总结
- 大数相乘 POJ2389
- 纯CSS3多列的瀑布流布局演示
- KVM 虚拟机的网络模式学习及配置
- #212 Space Replacement
- 深圳超爽der
- java有关于方法调用的几个例子
- Nginx反向代理的配置两个例子
- 浙大pat甲级 1023
- 编写一个memmove函数,实现内存拷贝
- Java并发同步之synchronized与volatile
- Bootstrap CSS3媒体查询断点
- shader学习(3)