假设输入的字符串还有足够的空间,将输入串内的空格替换为%20
例如:
输入: “Mr John Smith ”, 13
输出: “Mr%20John%20Smith”
采用队列实现该算法,空间复杂度最大O(n), 最好O(1)
时间复杂度O(n)
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
void URLify(char * s, int len) {
if(len < 1)
return;
std::queue<char> Queue;
bool hasBlank = false;
for (int i = 0; i < len || !Queue.empty(); ++i) {
// scan char from the string.
if(i < len) {
if(s[i] == ' ') {
hasBlank = true;
Queue.push('%');
Queue.push('2');
Queue.push('0');
}
else if (hasBlank)
Queue.push(s[i]);
}
if(!Queue.empty()) {
s[i] = Queue.front();
Queue.pop();
}
}
}
int main()
{
char s[255] = "Smith has properties";
URLify(s, strlen(s));
cout << s << endl;
return 0;
}