本文參考自《劍指offer》一書,代碼采用Java語言。
題目
請實現一個函數,把字符串中的每個空格替換成"%20"。例如輸入“We are happy.”,則輸出“We%20are%20happy.”。
思路
首先要詢問面試官是新建一個字符串還是在原有的字符串上修改,本題要求在原有字符串上進行修改。
若從前往后依次替換,在每次遇到空格字符時,都需要移動后面O(n)個字符,對於含有O(n)個空格字符的字符串而言,總的時間效率為O(n2)。
轉變思路:先計算出需要的總長度,然后從后往前進行復制和替換,,則每個字符只需要復制一次即可。時間效率為O(n)。
測試用例
1.字符串中無空格
2.字符串中含有空格(連續空格,空格在首尾等)
3.字符串為空字符串或者為null
完整Java代碼
1.根據牛客網的編程練習參考,方法的輸入為StringBuffer(String無法改變長度,所以采用StringBuffer),輸出為String。
主程序中,可以利用 StringBuffer sBuffer = new StringBuffer(str); 來獲得字符串的StringBuffer。
2.代碼中包含測試代碼
/** * * @Description 替換空格 * * @author yongh * @date 2018年7月18日 上午11:25:52 */ // 題目:請實現一個函數,把字符串中的每個空格替換成"%20"。例如輸入“We are happy.”, // 則輸出“We%20are%20happy.”。 public class ReplaceSpaces { /** * 實現空格的替換 */ public String replaceSpace(StringBuffer str) { if (str == null) { System.out.println("輸入錯誤!"); return null; } int length = str.length(); int indexOfOriginal = length-1; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ' ') length += 2; } str.setLength(length); int indexOfNew = length-1; while (indexOfNew > indexOfOriginal) { if (str.charAt(indexOfOriginal) != ' ') { str.setCharAt(indexOfNew--, str.charAt(indexOfOriginal)); } else { str.setCharAt(indexOfNew--, '0'); str.setCharAt(indexOfNew--, '2'); str.setCharAt(indexOfNew--, '%'); } indexOfOriginal--; } return str.toString(); } // ==================================測試代碼================================== /** * 輸入為null */ public void test1() { System.out.print("Test1:"); StringBuffer sBuffer = null; String s = replaceSpace(sBuffer); System.out.println(s); } /** * 輸入為空字符串 */ public void test2() { System.out.print("Test2:"); StringBuffer sBuffer = new StringBuffer(""); String s = replaceSpace(sBuffer); System.out.println(s); } /** * 輸入字符串無空格 */ public void test3() { System.out.print("Test3:"); StringBuffer sBuffer = new StringBuffer("abc"); String s = replaceSpace(sBuffer); System.out.println(s); } /** * 輸入字符串為首尾空格,中間連續空格 */ public void test4() { System.out.print("Test4:"); StringBuffer sBuffer = new StringBuffer(" a b c "); String s = replaceSpace(sBuffer); System.out.println(s); } public static void main(String[] args) { ReplaceSpaces rs = new ReplaceSpaces(); rs.test1(); rs.test2(); rs.test3(); rs.test4(); } }

Test1:輸入錯誤! null Test2: Test3:abc Test4:%20a%20b%20%20c%20%20
收獲:
1. 如果在從前往后進行復制時,需要多次移動數據,則可以考慮從后往前復制,從而減小移動次數,提高效率。
2. sb.setLength()方法、sb.setCharAt()方法記住