【剑指offer】字符串替换

时间:2023-03-08 20:35:20
【剑指offer】字符串替换

请实现一个函数,将一个字符串中的每个空格替换成“%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++;
             }
         }