转载指明出处
原题:
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".
翻译:
将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:(下面这样的形状)
P A H N
A P L S I I G
Y I R
之后按逐行顺序依次排列:"PAHNAPLSIIGYIR"
实现一个将字符串进行指定行数的转换的函数:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) 应当返回 "PAHNAPLSIIGYIR" 。
题目的意思就是按照如图规则转换:
/**
* Create with IntelliJ IDEA
* Author : wangzhenpeng
* Date : 2018/3/20
* Time : 下午5:30
* Description : Z型转换
* email : wangzhenpeng0924@163.com
*/
public class Solution {
public String convert(String s, int numRows) {
StringBuffer sb = new StringBuffer();
if (s.length() <= 0) {
return sb.toString();
}
if (numRows <= 1) {
return s;
}
//////////////////////
// 计算逻辑二维数组列数
int groupNum = numRows * 2 - 2;
//完整分组个数
int groupCount = s.length() / groupNum;
// 不完整分组长度
int mod = s.length() % groupNum;
// 列数
int numColumns = mod <= numRows ? groupCount * 2 + 1 : groupCount * 2 + 2;
//////////
// 循环输出
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numColumns; j++) {
// 处理第一行和最后一行
if ((i == 0 || i == numRows - 1) && j % 2 != 0) {
continue;
}
int index = generateIndex(s, i,j,numRows);
if (index >= 0) {
sb.append(s.charAt(index));
}
}
}
return sb.toString();
}
int generateIndex(String input, int numRow, int numColumn, int numRows) {
int index;
int groupCount = numColumn / 2;
int groupNum = numRows * 2 - 2;
index = numColumn % 2 == 0 ? groupCount * groupNum + numRow : (groupCount + 1) * groupNum - numRow;
return index < input.length() ? index : -1;
}
}