替换空格
题目
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
思路1:
这里leetcode上C++给出的是一个string,直接使用string.replace(),考虑到一个字符串中可能有多个空格,用string.find()找空格,如果未找到,则返回string.npos。如果是char数组,可以考虑思路2。
思路2:
按照剑指提供的思路,需要考虑替换后内存的大小,先统计空格个数,再申请一个新的字符串,从后往前进行赋值。
python里也有str.replace(),似乎时间复杂度高;str.count()似乎也比较高,所以这里python使用剑指的思路实现,先把str转换成list,最后再将list转换成str,比较麻烦。
总结:
C++里面string还是比char数组方便。
string.find()找不到时会返回string,npos,找到时会返回下标序号。
合并字符串或数组时,逆序可能会减少元素移动次数。
C++
class Solution {
public:
string replaceSpace(string s) {
string temp = "%20";
while(s.find(' ')!=s.npos)
{
s = s.replace(s.find(' '), 1,temp);
}
return s;
}
};
python
class Solution:
class Solution:
def replaceSpace(self, s: str) -> str:
if len(s)==0:
return s
s = list(s)
old_length = len(s)
i = 0
space_num = 0
while i!=old_length:
if s[i]==" ":
space_num+= 1
i+=1
new_length = old_length + space_num*2
p1 = old_length-1
p2 = new_length-1
ss = [0]*new_length
while (p1 >= 0) :
if s[p1]==" ":
ss[p2]="0"
p2 -=1
ss[p2]="2"
p2-=1
ss[p2]="%"
p2-=1
else:
ss[p2] = s[p1]
p2-=1
p1-=1
sss = ""
for each in ss:
sss+=str(each)
return sss