[剑之offer] 05 Replace space

1. The problem?

1. Description

Please implement a function to replace each space in the string s with "%20".

2. Example

Input: s = "We are happy."

Output: "We%20are%20happy."

3. Restrictions:

0 <= length of s <= 10000

package com.haoxiansheng.demo01.SwordfingerOffer;

import lombok.extern.slf4j.Slf4j;

/**
 * @author flame
 * @data 2020/10/15
 */
@Slf4j
public class ReplaceSpace {
    
    
    // 遍历替换
    public static void main(String[] args) {
    
    
        String test = "1 7 uit op";
        log.info("data=>{}, replaceSpace=>{}", test, replaceSpace(test));
    }
    // 复杂度分析:
    //时间复杂度 O(N) : 遍历使用 O(N) ,每轮添加(修改)字符操作使用 O(1) ;
    //空间复杂度 O(N) :  Java 新建的 StringBuilder 都使用了线性大小的额外空间。
    public static String replaceSpace(String s) {
    
    
        StringBuilder result = new StringBuilder();
        for(Character c : s.toCharArray())
        {
    
    
            if(c == ' ') result.append("%20");
            else result.append(c);
        }
        return result.toString();
    }
}

Guess you like

Origin blog.csdn.net/qq_40996741/article/details/109107991