Java解法:(小白易懂) 时间复杂度O(n),搞定 Offer 就靠它了
话不多说,直接看代码
/**
* @author Kongguan shaonv
* @date 2019/9/15 15:36
*
*/
public class Replace {
public static String replaceSpace(StringBuffer str) {
if (str == null || str.length() <= 0)
return null;
//计算空格数
int len = str.length();
int numberOfBlank = 0;
for (int i = 0; i < len; i++) {
if (str.charAt(i) == ' ')
numberOfBlank++;
}
//newLength为把空格替换为%20之后的总长度
int newLength = len + numberOfBlank * 2;
str.setLength(newLength); //更新字符串长度
//设置两个指针,p1 指向原字符串的最后一个字符的位置, p2 指向把空格替换为%20之后的最后一个字符的位置
int p1 = len - 1;
int p2 = newLength - 1;
while (p1 >= 0 && p2 > p1){
if (str.charAt(p1) == ' '){
str.setCharAt(p2--, '0');
str.setCharAt(p2--, '2');
str.setCharAt(p2--, '%');
}
else
str.setCharAt(p2--, str.charAt(p1));
p1--;
}
return str.toString();
}
public static void main(String[] args) {
//测试用例
StringBuffer str = new StringBuffer("Process finished with exit code 0.");
System.out.println(replaceSpace(str));
}
}

京公网安备 11010502036488号