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 N
*A P L S I I G
*Y I R
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)和一個目標行數(nRows)。要求咱們在‘之字形’從新排列這個字符串後,再按正常的從上到下,從左至右的順序輸出拼接好的字符串。app
之字形字符排列順序如圖ui
public String convert(String s, int numRows) { if(numRows == 1 || s.length() < numRows)return s; StringBuilder[] res = new StringBuilder[numRows]; int period = numRows*2 -2; for(int i=0;i<res.length;i++){ res[i]=new StringBuilder(""); } for(int i=0;i<s.length();i++){ int remainder = i % period ; if(remainder > numRows-1){ res[period-remainder].append(s.charAt(i)); continue; } res[remainder] = res[remainder].append(s.charAt(i)); } String resStr = ""; for(StringBuilder str : res){ resStr += str; } return resStr; }