劍指offer第五題 替換空格

2021-08-20 20:22:32 字數 1528 閱讀 5585

思路應該使用指標從後向前替換字串。不過python用不到。

class solution:

# s 源字串

def replacespace(self, s):

# write code here

new_s=''

for j in s:

if j==' ':

new_s=new_s+'%20'

else:

new_s=new_s+j

return new_s

特別的,if==' '。是因為python不允許在

if語句

的條件中賦值。所以if 1=2 會報錯(

還可以使用replace函式

class solution:

# s 源字串

def replacespace(self, s):

# write code here

return s.replace(' ','%20')

不過算是賴皮。

最後c++方法(從左至右遍歷,從右至左替換)

//思路

//1:從前往後插入,這樣移動·的次數多不建議

//2:從後往前插入

class solution {

public:

void replacespace(char *str,int length) {

//遍歷一邊字串找出空格的數量

if(str==null||length<0)

return ;

int i=0;

int oldnumber=0;//記錄以前的長度

int replacenumber=0;//記錄空格的數量

while(str[i]!='\0')

oldnumber++;

if(str[i]==' ')

replacenumber++;

i++; 

int newlength=oldnumber+replacenumber*2;//插入後的長度

if(newlength>length)//如果計算後的長度大於總長度就無法插入

return ;

int poldlength=oldnumber; //注意不要減一因為隱藏個『\0』也要算裡

int pnewlength=newlength;

while(poldlength>=0&&pnewlength>poldlength)//放字元

if(str[poldlength]==' ') //碰到空格就替換

str[pnewlength--]='0';

str[pnewlength--]='2';

str[pnewlength--]='%';

else //不是空格就把poldlength指向的字元裝入pnewlength指向的位置

str[pnewlength--]=str[poldlength];

poldlength--; //不管是if還是elsr都要把poldlength前移

《劍指offer》第五題(替換空格)

替換空格 include using namespace std bool replace space char str,const intlength int new length true length 2 count 演算法核心思想,從尾到頭複製 if new length length 要判...

劍指offer 題5 替換空格

題目 首先拿到題目,第一感覺就是乙個 空格 變成了 20 那字串長度肯定變長啊 所以我第一反應是建立新的字串b,然後從a乙個個讀取字元,遇到 空格 就用 20 來替代,只要b空間足夠,遍歷一遍就成了。但是,面試再簡單也不是考這種題目。於是這時候面試官可能會講了 要求在原來的字串上進行操作 這時候問題...

劍指offer 替換空格

思路 首先遍歷字串,找出空格的數量countspace,計算變換後的總長為newlength str.length 2 countspace。定義心得字元陣列,長度為newlength 從字串的後面開始複製和替換,如果不是空格,就複製,如果是空格,就變為 20.難點 牛客網上傳入引數是stringb...