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”行書寫,如圖所示。根據輸入的字符串和行數做如下變換:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGY
分析
這個題看懂題意是關鍵。主要是提取相應位置的坐標,組成新的字符串
-
行數n=2時
n=2 -
行數n=3時
n=3 -
行數n=4時
n=4
根據上面三幅圖分析,分為如下幾個步驟:
- 紅色部分字符個數為
2n-2
(其中n為行數) - 每個列間相鄰的兩個字符的索引數相差
2n-2
(暫時不管斜線上的字符) - 看斜線上的字符,索引總是
j+(2n-2)-2i
(其中j為列索引,i為行索引,需要聯系下面代碼for循環中理解)
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;//向下數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);
}
}