国外便宜的云服务器西安seo优化工作室
⭐️ 题目描述
🌟 leetcode链接:面试题 01.03. URL化
思路: 计算出空格的个数,我们可以知道最后一个字符的位置 endPos
,再从后 end
向前遍历若不是空格正常拷贝,是空格则替换成 %20
,最终当空格替换完成的时候,endPos
和 end
两个下标会相遇。
代码:
char* replaceSpaces(char* S, int length) {// 计算空格个数int count = 0;for (int i = length - 1; i >= 0; i--) {if (S[i] == ' ') count++;}// 计算最后一个字符的最终位置int endPos = length - count + count * 3;S[endPos--] = 0;// 最后一个字符当前位置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;
}