Lc_剑指Offer05替换空格

双指针
package com.leetcode.leetcode.licm;
/**
 * @description: 剑指 Offer 05. 替换空格
 * 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
 * <p>
 * <p>
 * <p>
 * 示例 1:
 * <p>
 * 输入:s = "We are happy."
 * 输出:"We%20are%20happy."
 * <p>
 * <p>
 * 限制:
 * <p>
 * 0 <= s 的长度 <= 10000
 * @author: licm
 * @create: 2021-07-12 10:47
 **/
public class Lc_剑指Offer05替换空格 {
    /**
     * * 第一步 检索当前字符串有多少个空格,然后进行扩容
     * <p>
     * 第二部 将空格从后向前替换,利用双指针
     *
     * @param s
     * @return
     */
    public static String replaceSpace(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                count++;
            }
        }
        char[] charS = s.toCharArray();
        char[] newCharS = new char[charS.length + count * 2];
        for (int i = charS.length - 1; i >= 0; i--) {
            newCharS[i] = charS[i];
        }
        int left = charS.length - 1;
        int right = newCharS.length - 1;
       while(left<right) {
            if (newCharS[left] == ' ') {
                newCharS[right] = '0';
                newCharS[right - 1] = '2';
                newCharS[right - 2] = '%';
                right -= 2;
            } else {
                newCharS[right] = newCharS[left];
            }
            left--;
            right--;
        }
        String newStr = new String(newCharS, 0, newCharS.length);
        return newStr;
    }
    public static void main(String[] args) {
        String s = "We are happy.";
        System.out.println(replaceSpace(s));
    }
}
下一节:Lc_面试题01_06_字符串压缩