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)
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 "PAHNAPLSIIGY
將給定的字符串以“Z”行書寫橄妆,如圖所示衙伶。根據(jù)輸入的字符串和行數(shù)做如下變換:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGY
分析
這個題看懂題意是關(guān)鍵。主要是提取相應(yīng)位置的坐標(biāo)害碾,組成新的字符串
-
行數(shù)n=2時
n=2 -
行數(shù)n=3時
n=3 -
行數(shù)n=4時
n=4
根據(jù)上面三幅圖分析矢劲,分為如下幾個步驟:
- 紅色部分字符個數(shù)為
2n-2
(其中n為行數(shù)) - 每個列間相鄰的兩個字符的索引數(shù)相差
2n-2
(暫時不管斜線上的字符) - 看斜線上的字符,索引總是
j+(2n-2)-2i
(其中j為列索引蛮原,i為行索引卧须,需要聯(lián)系下面代碼for循環(huán)中理解)
java代碼
public class Solution {
public String convert(String s, int numRows) {
int s_length = s.length();
if (s_length <= numRows || numRows == 1) return s;
char[] result = new char[s_length];
int size_1 = 2 * numRows - 2;//向下數(shù)size_1個字符即為要添加到result中的字符
int count = 0;
for (int i = 0; i < numRows; i ++) {//表示行
for (int j = i; j < s_length; j += size_1) {//表示列
result[count ++] = s.charAt(j);
if (i != 0 && i != numRows - 1) {//如果不是第一行和最后一行
int temp = j +size_1 -2 * i;//下一個要加入result中的字符索引
if (temp < s_length) {
result[count ++] = s.charAt(temp);//不能超過字符的長度
}
}
}
}
return new String(result);
}
}