lintcode--空格替换
来源:互联网 发布:rest in peace知乎 编辑:程序博客网 时间:2024/05/18 02:14
设计一种方法,将一个字符串中的所有空格替换成 %20
。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。
你的程序还需要返回被替换后的字符串的长度。
注意事项
如果使用 Java 或 Python, 程序中请用字符数组表示字符串。
对于字符串"Mr John Smith"
, 长度为 13
替换空格之后,参数中的字符串需要变为"Mr%20John%20Smith"
,并且把新长度 17
作为结果返回。
/*public class Solution {
public int replaceBlank(char[] string, int length) {
// Write your code here
if(0==length) return 0;
int num = 0;
for(int i=0;i<length;i++){
if(string[i] == ' ') num++;
}
int newLen = length + num*2;
string[newLen] = 0;
int j = 1;
for(int i=length-1;i>=0;i--){
if(string[i] != ' '){
string[newLen - j] = string[i];
j++;
}
else{
string[newLen - j] = '0';
j++;
string[newLen - j] = '2';
j++;
string[newLen - j] = '%';
j++;
}
}
return newLen;
}
}*/
/*直接在原char字符数组上操作,先求新的字符串数组的长度,再从后插入%20,这样就解决了,对于从后插入求解的碰到过,题目都会给这样的提示:
//假设该字符串有足够的空间来加入新的字符,要根据题目找答案,找思路。
求出新的字符数组的长度,将空格的位置替换为%20,这里从后开始遍历,遇到空格就将其替换为%20。这里从后向前遍历的原因是因为其时间效率比从前往后遍历要高(因为从前往后遍历遇到空格时需要将空格后面所有的字符向后移动2个位置,而从后向前则不需要)
*/
public class Solution {
public int replaceBlank(char[] string, int length) {
int reallen = length;
for(int i = 0;i<length;i++){
if(string[i] == ' ')
reallen += 2;//加2为之后长度
}
int index = reallen;
for(int i = length - 1;i>= 0 ;i-- ){
if(string[i] == ' '){
--index;
string[index] = '0';
string[--index] = '2';
string[--index] = '%';
}else{
string[--index] = string[i];
}
}
//新长度
return reallen;
}
}
- Lintcode空格替换
- lintcode-空格替换-212
- 空格替换(LintCode)
- lintcode 空格替换
- LintCode:空格替换
- lintcode ----空格替换
- LintCode 空格替换
- 【LintCode】 空格替换
- lintcode,空格替换
- Lintcode 空格替换
- lintcode--空格替换
- LintCode 212 空格替换
- [LintCode]212.空格替换
- LintCode:空格替换
- 空格替换-LintCode
- LintCode-剑指Offer-空格替换
- 空格替换
- 替换空格
- 归一化、标准化和正则化的关系
- String类的实现
- 2017 Multi-University Training Contest
- DOM
- 图像处理26:图像金子塔
- lintcode--空格替换
- Zookeeper Leader选举
- 矩阵快速幂详解
- 216. Combination Sum III
- JavaScript-运算符&&(与、并且)判断一个数字是否是两位数
- this与super关键字
- lua解析json
- 内部类
- CNN的发展史