写了一个,用了很多额外空间
发现开辟一个字符数组,最后再转换成string,与直接用各个string块 加起来 速度一样啊。
是因为string优化的太好了,还是最后数组转换为字符串耗时间呢?
C++ 代码
class Solution {
public:
string replaceSpaces(string &str) {
string re = "";
unsigned int ll = 0,rr = 0;
while(rr<str.size())
{
if(str[rr] == ' ')
{
re += str.substr(ll,rr-ll) + "%20";
++rr;
ll = rr;
}
else
++rr;
}
re += str.substr(ll,rr-ll);
return re;
}
};
C++ 代码
public:
string replaceSpaces(string &str) {
int spaceNum = 0;
for(int i = 0; i<str.size(); ++i)
{
if(str[i] == ' ')
++spaceNum;
}
int N = str.size() + 1 + 2*spaceNum;
char* re = new char[N--];
re[N--] = '\0';
int pivot = str.size() - 1;
while(N>=0)
{
if(str[pivot] == ' ')
{
re[N--] = '0';
re[N--] = '2';
re[N--] = '%';
}
else
{
re[N--] = str[pivot];
}
pivot--;
}
std::string reTemp(re);
delete[] re;
return reTemp;
}