深圳專業(yè)專業(yè)網(wǎng)站建設(shè)公司搜索引擎在線
?? 題目描述
🌟 leetcode鏈接:面試題 01.03. URL化
思路: 計(jì)算出空格的個(gè)數(shù),我們可以知道最后一個(gè)字符的位置 endPos
,再?gòu)暮?end
向前遍歷若不是空格正??截?#xff0c;是空格則替換成 %20
,最終當(dāng)空格替換完成的時(shí)候,endPos
和 end
兩個(gè)下標(biāo)會(huì)相遇。
代碼:
char* replaceSpaces(char* S, int length) {// 計(jì)算空格個(gè)數(shù)int count = 0;for (int i = length - 1; i >= 0; i--) {if (S[i] == ' ') count++;}// 計(jì)算最后一個(gè)字符的最終位置int endPos = length - count + count * 3;S[endPos--] = 0;// 最后一個(gè)字符當(dāng)前位置int end = length - 1;while (endPos != end) {if (S[end] != ' ') {S[endPos--] = S[end--];}else {S[endPos--] = '0';S[endPos--] = '2';S[endPos--] = '%';end--;}}return S;
}