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; }