当前位置:网站首页>[jzof] 05 replace spaces

[jzof] 05 replace spaces

2022-07-24 21:05:00 Sighed, angry

import java.util.*;
public class Solution {
    
    /** *  The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly  * * * @param s string character string  * @return string character string  */
    public String replaceSpace(String s) {
    
        if (s.length() == 0){
    
            return s;
        }
        int blankNum = 0;

        // Calculate the number of spaces 
        for (int i = 0; i < s.length(); i++) {
    
            if (s.charAt(i) == 32){
    
                blankNum++;
            }
        }
        // The length of the array after replacement 
        int newStrLen = s.length() + blankNum*2;
        // Expand the source string 
        char[] chars = Arrays.copyOf(s.toCharArray(), newStrLen);
        int oldEndIndex = s.length() -1;
        int newEndIndex = newStrLen - 1;
        for (;oldEndIndex>=0;oldEndIndex--,newEndIndex--){
    
            if (oldEndIndex == newEndIndex){
    
                return new String(chars);
            }
            if (s.charAt(oldEndIndex) == 32){
    
                chars[newEndIndex] = '0';
                chars[--newEndIndex] = '2';
                chars[--newEndIndex] = '%';
            }else {
    
                chars[newEndIndex] = s.charAt(oldEndIndex);
            }
        }
        return new String(chars);
    }
}
原网站

版权声明
本文为[Sighed, angry]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/202/202207201844468762.html