替换空格
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
Java
问题1:替换字符串,是在原来的字符串上做替换,还是新开辟一个字符串做替换?
问题2:在当前字符串替换,怎么替换才更有效率(不考虑java里现有的replace方法)
从前往后替换,后面的字符要不断往后移动,要多次移动,所以效率低下
从后往前,先计算需要多少空间,然后从后往前移动,每个字符只移动一次,效率高一点
两种思路:
public class Solution {
public String replaceSpace(StringBuffer str) {
if(str==null){
return null;
}
StringBuilder newStr = new StringBuilder();
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' '){
newStr.append('%');
newStr.append('2');
newStr.append('0');
}else{
newStr.append(str.charAt(i));
}
}
return newStr.toString();
}
}
直接replace
public class Solution {
public String replaceSpace(StringBuffer str) {
if(str==null)
{
return null;
}
for(int i=0;i<str.length();i++)
{
char c = str.charAt(i);
if(c==' ')
{
str.replace(i,i+1,"%20");
}
}
String newstr = str.toString();
return newstr;
}
}
C++
思路:从前向后记录空格数目,从后向前替换空格。
重点:从后向前替换的时候的技巧,例如:“we are lucky”
0 1 2 3 4 5 6 7 8 9 10 11
w e a r e l u c k y
可以得知count=2; //空格的个数
所以在替换的时候7~11的字母要向后移动count×2个位置,3~5字母要向后移动(count-1)×2个位置
所以得到 :
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
w e a r e l u c k y
w e a r a r e u c k l u c k y
在替换的时候直接在空格处写入%20
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
w e a r e l u c k y
w e % 2 0 a r e % 2 0 l u c k y
class Solution {
public:
void replaceSpace(char *str,int length) {
int count=0;
for(int i=0;i<length;i++){
if(str[i]==' ')
count++;
}
for(int i=length-1;i>=0;i--){
if(str[i]!=' '){
str[i+2*count]=str[i];
}
else{
count--;
str[i+2*count]='%';
str[i+2*count+1]='2';
str[i+2*count+2]='0';
}
}
}
};
Python
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = list(s)
count=len(s)
for i in range(0,count):
if s[i]==' ':
s[i]='%20'
return ''.join(s)