原题目
面试题 01.03. URL化
URL化。编写一种方法,将字符串中的空格全部替换为%20
。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java
实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
输入:"Mr John Smith ", 13
输出:"Mr%20John%20Smith"
示例2:
输入:" ", 5
输出:"%20%20%20%20%20"
提示:
- 字符串长度在[0, 500000]范围内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-url-lcci/
第一遍解法
遍历字符串,在空格处s2 += “%20”,否则s2 += S[i]。
class Solution {
public:
string replaceSpaces(string S, int length) {
string s2 = "";
for (int i = 0; i < S.size(); i++) {
if (S[i] == ' ') {
if (i + 1 <= length) {
s2 += "%20";
}
else {
return s2;
}
}
else {
s2 += S[i];
}
}
return s2;
}
};
时间复杂度: O(n)
空间复杂度: O(n)
网上好的解法
采用双指针,题目前提为字符串尾部有足够的空间存放新增字符,所以此处使用了S.size()大于URL化后字符串的大小这个假设。所以最后还要进行substr。
从后至前,依次遍历,赋值,更新指针。
class Solution {
public:
string replaceSpaces(string S, int length) {
int i = length - 1;
int j = S.size() - 1;
while(i >= 0) {
if (S[i] == ' ') {
S[j--] = '0';
S[j--] = '2';
S[j--] = '%';
i--;
} else {
S[j--] = S[i--];
}
}
return S.substr(j+1);
}
};
时间复杂度: O(n)
空间复杂度: O(1)
最后的代码
优化了第一次的解法,(字符串’+='会提高效率)思路一样。
class Solution {
public:
string replaceSpaces(string S, int length) {
string s2 = "";
for (int i = 0; i < length; i++) {
if (S[i] == ' ') { s2 += "%20"; }
else { s2 += S[i]; }
}
return s2;
}
};
时间复杂度: O(n)
空间复杂度: O(n)
思考
- string要经常使用“+=”,效率高很多。
- 对字符串的题目,要经常思考双指针能否解决此问题,双指针通常在空间复杂度上比较低。