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)
P A H NA P L S I I GY I RAnd 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"
.Subscribe to see which companies asked this question.
題目理解:將輸入的字符串,字符順序重排后輸出,可以簡單理解為將一維向量轉換為了二維的矩陣,最后將二維矩陣又拼接成一維向量返回。重排規則:zigzag,之字形掃描。解決的大體思路:根據輸入的之子寬度參數nRows,將text不同下標的字符散列到不同行的字符串中,最后按行重新拼接起來。為了方便追加字符,每一行使用的是StringBuilder result[nRows]。eg:
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 |
public class Solution { public String convert(String s, int numRows) { StringBuilder[] result=new StringBuilder[numRows]; char[] array=s.toCharArray(); for(int i=0;i<numRows;i++)result[i]=new StringBuilder(s.length()); //對每一個stringbulider初始化 int i=0,loc=0; while(i<s.length()){ for(loc=0;loc<numRows && i<s.length();i+=1,loc+=1){ result[loc].append(array[i]); }//由0開始的行號上升過程,同時字符串指示下標也要移動 for(loc=numRows-2;loc>0 && i<s.length();i+=1,loc-=1){ result[loc].append(array[i]); }//由numRows-2開始的行號下降過程,同時字符串指示下標也要移動 } for(i=1;i<numRows;i++){ result[0].append(result[i]); } return result[0].toString(); }}(2)注意到,在字符散列進result[]的行號會有增加和減小兩個過程,利用邊界值0和nRows-1,來改變待散列指示標記loc的移動方向,即可完成正確散列。值得注意的是,使用該思路需要留意nRows為1的情況,需要在代碼的最開始做出特殊情況處理。代碼:public class Solution { public String convert(String s, int numRows) { if(s.length()<=numRows||numRows==1)return s; StringBuilder[] result=new StringBuilder[numRows]; char[] array=s.toCharArray(); int len=s.length(); for(int i=0;i<numRows;i++)result[i]=new StringBuilder(len); int i=0,loc=0,step=1; while(i<len){ result[loc].append(array[i]); if(loc==numRows-1)step=-1; //下標減小 if(loc==0)step=1; //下標增加 loc+=step; i+=1; } for(i=1;i<numRows;i++){ result[0].append(result[i]); } return result[0].toString(); }}
新聞熱點
疑難解答