华企号 后端开发 #yyds干货盘点# LeetCode程序员面试金典:URL化

#yyds干货盘点# LeetCode程序员面试金典:URL化

URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)

 

示例 1:

输入:”Mr John Smith    “, 13

输出:”Mr%20John%20Smith”

示例 2:

输入:”               “, 5

输出:”%20%20%20%20%20”

代码实现:

class Solution {
public String replaceSpaces(String S, int length) {

// 边界条件
if(S == null || S.length() == 0) {
return S;
}

char[] str = S.toCharArray();
// 双指针位置
int preIndex = length – 1;
int lastIndex = preIndex;
for(int i=0; i < length; i++) {
if(str[i] == ‘ ‘) {
lastIndex +=2;
}
}

// 替换字符串
while(lastIndex != preIndex) {
if(str[preIndex] != ‘ ‘) {
// 复制
str[lastIndex] = str[preIndex];
lastIndex–;
preIndex–;
} else {
// 替换 0 2 % ; pre-1; last – 3
str[lastIndex –] = ‘0’;
str[lastIndex –] = ‘2’;
str[lastIndex –] = ‘%’;
preIndex –;
}
}

return String.valueOf(str).trim();
}
}

 

作者: 华企网通王鹏程序员

我是程序员王鹏,热爱互联网软件开发和设计,专注于大数据、数据分析、数据库、php、java、python、scala、k8s、docker等知识总结。 我的座右铭:"业精于勤荒于嬉,行成于思毁于随"
上一篇
下一篇

发表回复

联系我们

联系我们

028-84868647

在线咨询: QQ交谈

邮箱: tech@68v8.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部