leetcode-6
*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 s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
*/
public class Solution6 {
public static String convert(String s, int numRows) {
//计算s的长度
int length=s.length();
//计算每组几个字符
int m=2*numRows-2;
//计有几组
int k=length/m+1;
//结果字符串
StringBuffer re=new StringBuffer();
//第一行
for(int i=0;i<length;i++) {
//输出每组第一个字符
if(i%m==0) {
re.append(s.charAt(i));
}
}
//第二行到第k-1行
for(int i=2;i<=numRows-1;i++) {
//第一第一组的第i行
for(int p=1;p<=k;p++) {
int first=i+(p-1)*m;
int second=m-(i-2)+(p-1)*m;
if(first<=length) {
re.append(s.charAt(first-1));
}
if(second<=length) {
re.append(s.charAt(second-1));
}
}
}
//最后一行
for(int i=0;i<length;i++) {
//输出每组第一个字符
if(i%m==numRows-1) {
re.append(s.charAt(i));
}
}
return re.toString();
}
}