1. 程式人生 > >【劍指offer】字符串替換

【劍指offer】字符串替換

etc substr public 大小 nts ace sub 一個 目標

請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串為We Are Happy.則經過替換之後的字符串為We%20Are%20Happy。

*StringBuffer 擴容 str.setLength(擴容大小)

*思路:將原字符數組擴容至目標大小後,從後往前移動字符串,可大大減小移動次數

public class Solution {

public String replaceSpace(StringBuffer str) {
int originalLength = str.length();
int capacityRequired = (calculateLength(str) << 1) + str.length();
//在原大小上擴容2*空格數
str.setLength(capacityRequired);
for(int i=originalLength-1, j=capacityRequired-1; i >= 0; i--, j--){
if(str.charAt(i)==‘ ‘){
str.setCharAt(j-2, ‘%‘);
str.setCharAt(j-1,‘2‘);
str.setCharAt(j, ‘0‘);
j=j-2;
}else{
str.setCharAt(j, str.charAt(i));
}
}

return str.toString().substring(0,capacityRequired);
}
private int calculateLength(StringBuffer str){
int countSpace = 0;
for(int i=0; i < str.length(); i++){
if(str.charAt(i)==‘ ‘){
countSpace++;
}
}

【劍指offer】字符串替換