2、替换空格
1、直接调用java自带函数
运行时间:24ms, 占用内存:9504K
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replace(" ","%20");
}
}PS:stringBuffer输出为string类型时一定要记得转换!
关于string,stringbuffer 和stringbuilder的区别的博客:https://blog.csdn.net/u011702479/article/details/82262823
2、双指针遍历
运行时间:17ms, 占用内存:9548K
【思路】:先遍历一遍,找出所有的空格,并计算出新的字符串长度(因为是stringBuffer类型,所以可以设定字符串长度),然后从尾向前遍历字符串,遇到空格就转换为“%20”,直到两个指针指向同一个位置,表明以没有空格存在。
public class Solution {
public String replaceSpace(StringBuffer str) {
int len1=str.length();
int len2=len1;
for(int i=0;i<len1;i++){
if (str.charAt(i) == ' '){
len2 =len2+2;
}
}
str.setLength(len2);
while(len1!=len2){
if (str.charAt(len1-1) == ' '){
str.setCharAt(len2-1, '0');
len2--;
str.setCharAt(len2-1, '2');
len2--;
str.setCharAt(len2-1, '%');
len2--;
}else{
str.setCharAt(len2-1, str.charAt(len1-1));
len2--;
}
len1--;
}
return str.toString();
}
}PS:字符串从后向前遍历时,charAt(index),index应该为len-1