Lc_劍指Offer05替換空格
阿新 • • 發佈:2021-07-12
不會,我可以學;落後,我可以追趕;跌倒,我可以站起來!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)); } }