題目:The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
意思就是大概就是
S.png
給一個(gè)字符串和行數(shù)奈梳,倒Z排列好了以后飞涂,最后返回的字符串是所有的行拼接起來(lái)的志珍。abcdefghijklmn汉形,numRows=5候学,輸出字符為aibhjcgkdflnem
思路:一開始就想好了把上下和中間分隔開來(lái)驯镊,這樣就簡(jiǎn)單一點(diǎn)锅锨,上和下的代碼都一樣敛苇,只是循環(huán)的起點(diǎn)不一樣妆绞,距離都是numRows+numRows-2,中間有點(diǎn)麻煩枫攀,剛開始想錯(cuò)了括饶,以為它每一丨都是從上到下依次的來(lái),寫完提交以后才發(fā)現(xiàn)是z字形的来涨,然后只要重寫中間的代碼就行图焰,仔細(xì)看了一下中間的數(shù)字規(guī)律就是:第一個(gè)字母不用說(shuō)是i,第二個(gè)是(numRows-i)2,第三個(gè)是i2-1,然后又是(numRows-i)*2,一直循環(huán)蹦掐,想了想只能靠一個(gè)boolean來(lái)控制這樣的轉(zhuǎn)換用來(lái)控制取字母的循環(huán)變量技羔。附上我的代碼:
public String convert(String s, int numRows) {
if(s=="")return "";
if(numRows<2)return s;
String result="";
boolean bian=true;
for(int i=0;i<s.length();i+=numRows+numRows-2) {
result+=s.charAt(i);
}
for(int i=1;i<numRows-1;i++) {
for(int j=i;j<s.length();j++) {
result+=s.charAt(j);
if(bian) {j+=(numRows-i-1)*2-1;bian=false;continue;}
if(!bian) {j+=i*2-1;bian=true;}
}
bian=true;
}
for(int i=numRows-1;i<s.length();i+=numRows+numRows-2) {
result+=s.charAt(i);
}
return result;
}
測(cè)試了一下別人的代碼和我的代碼僵闯,別人用了1ms,我用了18藤滥。鳖粟。。超陆。牺弹。
好好研究學(xué)習(xí)一下,這一篇文章就這樣
public String convert(String s, int nRows) {
char[] c = s.toCharArray();
int len = c.length;
StringBuffer[] sb = new StringBuffer[nRows];
for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();
int i = 0;
while (i < len) {
for (int idx = 0; idx < nRows && i < len; idx++) // vertically down
sb[idx].append(c[i++]);
for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up
sb[idx].append(c[i++]);
}
for (int idx = 1; idx < sb.length; idx++)
sb[0].append(sb[idx]);
return sb[0].toString();
}