题目:
代码:
c++ STL 方法 时间复杂度高
class Solution {
public:
string replaceSpace(string s) {
int pos = s.find(' ');
while(pos != -1)
{
s.erase(pos,1);
s.insert(pos,"%20");
pos = s.find(' ');
}
return s;
}
};
代码片段2:
class Solution {
public:
string replaceSpace(string s) {
int Oldlength = s.size();
int num = 0;
int i = 0;
while(s[i] != '\0')
{
if (s[i] == ' ')
num ++;
i++;
}
int Newlength = Oldlength + 2*num;
s.resize(Newlength);
int Oldindex = Oldlength;
int Newindex = Newlength;
while(Oldindex >= 0 && Oldindex < Newindex)
{
if(s[Oldindex] == ' ')
{
s[Newindex--] = '0';
s[Newindex--] = '2';
s[Newindex--] = '%';
}
else
{
s[Newindex--] = s[Oldindex];
}
Oldindex--;
}
return s;
}
};
思想:从前往后填写,在字符串移动过程中 部分子串涉及多次移动,时间复杂度为O(n),而从后往前不存在此问题 为O(n)。
代码片段3:
class Solution {
public:
string replaceSpace(string s) { //字符数组
string array; //存储结果
for(auto &c : s){ //遍历原字符串
if(c == ' '){
array += "%20";
}
else{
array += c;
}
}
return array;
}
};
附加题:
有两个排序的数组a b ,实现b中的数字插入a中,并有序。
从头到尾比较易出现移动多次情况,而从后往前比较则无这个问题:
代码:
int main()
{
int a[10] = {0,1,2,3,4};
int b[5] = {0,1,4,6,7};
int indexa = 4;
int index = 9;
int indexb = 4;
while (indexa >= 0 && indexb >= 0)
{
if(a[indexa] >= b[indexb])
{
a[index--] = a[indexa];
indexa--;
}
else
{
a[index--] = b[indexb];
indexb--;
}
}
for(int i = 0; i < 10; i++)
{
cout << a[i];
}
cout << endl;
return 0;
}