Skip to content
本页目录

05-替换空格

题目描述

https://leetcode.cn/problems/ti-huan-kong-ge-lcof/

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 示例 1:

输入:s = "We are happy."
输出:"We%20are%20happy."

限制:

0 <= s 的长度 <= 10000

思路分析

  • 本题如果使用库函数则可以很快实现,但是这个不是面试官期望的答案
  • 基本思路: 首先要侦测出几个空格,然后将新的数组拓展为 s.Length + n*2 的长度 然后从后往前替换,从后往前替换的原因是可以只循环一次就替换完所有字符串 注意:从后往前是C++的方式,没有开辟新数组,而是在原来的数组追加了长度达成的效果,如果是C#开辟了一个新的字符串数组,那么从前往后循环也是一样的

实现代码

csharp
public class Solution {
    public string ReplaceSpace(string s) {
        //return s.Replace(" ","%20");
        //思路,不能使用类库,扩展字符串长度为 length + 空格 * 2
        //从后面开始往前替换
        int count = 0;
        for(int i = 0; i<s.Length ; i++){
            if(s[i] == ' '){
                count ++;
            }
        }
        //构造新array
        char[] result = new char[s.Length + count * 2];
        //从后往前填入数组
        int sourceIndex = s.Length - 1;
        int targetIndex = s.Length + count * 2 -1;
        while(sourceIndex>=0){
            if(s[sourceIndex] != ' '){
                result[targetIndex] = s[sourceIndex];
                sourceIndex-=1;
                targetIndex-=1;
            }
            else{
                result[targetIndex-2] = '%';
                result[targetIndex-1] = '2';
                result[targetIndex] = '0';
                sourceIndex-=1;
                targetIndex-=3;
            }
        }
        string str = new string(result);
        return str;
    }
}

Released under the MIT License.