考慮對字符串進行以下轉換。給定一個行和一個字符串作爲輸入,將該字符串在行中來回寫入。例如,給定輸入什麼是更好的曲折印刷更好的解決方案?
請轉換我定製的曲折打印格式
有三排,我們會寫這樣一個曲折的字符串:
P s n t o s i z a i n r
l a e o v r m t a u t m z d i z g r n i g o m t
e c e e c o e g p t f a
(請不要編輯這個打印輸出,這是必需的輸出,它不是一個真正的曲折,它是一個定製的鋸齒形的 )
最後,我們串連每行的比賽合力得到結果字符串
Psntosizainrlaeovrmtautmzdizgrnigomteceecoegptfa
我對這個問題,我已經在這裏僞代碼寫出來的算法的草圖:
it is asking about the relationship between {index} and {output row and col}
Def:
down = false;
up = false;
r=0;
c=0;
char[][] output;
there are three cases here:
case 1:
index % 4 == 0, it is the beginning of a down printing
r = 0;
output[r][c] = in.charAt(index);
c++;
down = true; up = false;
case 2:
index%4 != 0 && down = true;
r = index % 4;
output[r][c] = in.charAt(index);
if(r == 2){ up = true; down = false; c++;} // when come to the last row of a down formatting
case 3:
index%4 != 0 && up == true;
r = 4- index%4;
output[r][c] = in.charAt(index);
c++;
對於一個通用的解決方案,我可以取代4作爲nRows+1
;
雖然我認爲這可行,但我並不太滿意。有沒有人有更清晰或更快的算法來解決這個問題?
這是功課嗎?如果是這樣,請標記爲這樣。此代碼不是java - 請適當地編輯您的代碼 – Bohemian
@Bohemian:它可能是僞代碼 –