【題目描述】
Write a method to replace all spaces in a string with%20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
Notice:If you are using Java or Python担钮,please use characters array instead of string.
設計一種方法瘟裸,將一個字符串中的所有空格替換成%20普泡。你可以假設該字符串有足夠的空間來加入新的字符峦树,且你得到的是“真實的”字符長度鸭叙。
你的程序還需要返回被替換后的字符串的長度酝惧。
【注】如果使用 Java 或 Python, 程序中請用字符數(shù)組表示字符串竟宋。
【題目鏈接】
www.lintcode.com/en/problem/space-replacement/
【題目解析】
先統(tǒng)計字符串中含有的空格數(shù)A,設原來長度為len,則最終字符串長度為len+A*2逻卖。
原問題轉換成一個兩點移動問題叨吮。設一個指針P1指向最終字符串尾部辆布,另一個P2指向原字符串尾部
分析P2字符:
如果不是空格,P2字符復制到P1,P1茶鉴、P2左移
如果是空格锋玲,P1填入三位%20,總供左移了3位,而P2左移1位
按3步驟不斷操作涵叮,最終兩指針一定會在字符串0索引位重合惭蹂。
【參考答案】