注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
题意一、新创建一个StringBuffer
public static String replaceSpace(StringBuffer str) {
if (str == null) return null;
StringBuffer newStr = new StringBuffer();
for (int i = 0; i < str.length(); i ++) {
if (str.charAt(i) == ' ')
newStr.append("%20");
else newStr.append(str.charAt(i));
}
return newStr.toString();
}
运行时间:14ms
占用内存:9420k
题意二、在原有StringBuffer上进行替换:用新旧尾指针,从后往前进行移动,当相遇时证明已经没有空格,停止移动
public class Solution {
public String replaceSpace(StringBuffer str) {
if (str == null) return null;
int spaceNum = 0;
for (int i = 0; i < str.length(); i ++) {
if (str.charAt(i) == ' ')
spaceNum ++;
}
int oldIndex = str.length() - 1;
int newIndex = oldIndex + spaceNum * 2;
str.setLength(newIndex + 1);
for (;oldIndex >= 0 && oldIndex < newIndex; oldIndex --) {
if (str.charAt(oldIndex) == ' ') {
str.setCharAt(newIndex --, '0');
str.setCharAt(newIndex --, '2');
str.setCharAt(newIndex --, '%');
} else {
str.setCharAt(newIndex --, str.charAt(oldIndex));
}
}
return str.toString();
}
}
运行时间:15ms
占用内存:9560k